Mypy报Unsupported operand types错误,混合类型字典问题求解
解决Mypy对混合类型字典的类型检查错误
问题场景
定义包含混合类型值的字典:
context = { 'a': {'a_sub': 0}, 'b': 1 } # 代码其他位置对b进行累加操作 context['b'] += 1
通过pre-commit运行Mypy时触发错误:
Unsupported operand types for + ("object" and "int")
当把a的值改为int类型后,Mypy不再报错——这是因为Mypy推断字典值类型为int | dict,无法确定context['b']一定是int类型,因此触发报错。需求为:允许字典包含任意类型的键值对,但明确b的值为int类型,修复该Mypy错误。
方案1:使用TypedDict(推荐)
通过TypedDict可以精确指定部分键的类型,同时允许其他任意键值对存在,是最规范的解决方案。
Python 3.11+ 版本(支持Unpack语法)
from typing import TypedDict, Unpack, Any class Context(TypedDict, total=False): b: int # 允许其他任意键值对 **kwargs: Any context: Context = { 'a': {'a_sub': 0}, 'b': 1 } context['b'] += 1 # Mypy不再报错
兼容旧版本Python
from typing import TypedDict, Any class Context(TypedDict, total=False): b: int # 标注为TypedDict与任意字典的联合类型 context: Context | dict[str, Any] = { 'a': {'a_sub': 0}, 'b': 1 } context['b'] += 1
优点:既保证b的类型安全,又允许字典包含其他任意键值对,完全符合类型检查规范。
方案2:使用类型断言
在访问context['b']时,用cast明确告诉Mypy该值为int类型:
from typing import cast context = { 'a': {'a_sub': 0}, 'b': 1 } cast(int, context['b']) += 1
注意:类型断言是开发者向Mypy做出的承诺,如果实际运行时context['b']不是int类型,会触发运行时错误,需确保业务逻辑的正确性。
方案3:显式标注字典类型为dict[str, Any]
直接将字典标注为任意值类型,让Mypy跳过对该字典的类型检查:
from typing import Any context: dict[str, Any] = { 'a': {'a_sub': 0}, 'b': 1 } context['b'] += 1
缺点:失去了对b的类型校验能力,若后续b被赋值为非int类型,Mypy无法发现问题,仅适合临时快速解决,不推荐长期使用。
内容的提问来源于stack exchange,提问作者J_yang
相关产品推荐
相关产品推荐

