我有这个代码
def my_foo(x: dict[str, int | float], some_condition: bool) -> None:
if some_condition:
x['the_int'] = 1
else:
x['the_float'] = 1.0
my_dict = {'some_int': 2}
my_foo(my_dict, True)
mypy(可以理解)抱怨
错误:“my_foo”的参数 1 不兼容 输入“字典[str,int]”;预期“dict[str, int | float]”[arg-type] 注意:“Dict”是不变的——参见 https://mypy.readthedocs.io/en/stable/common_issues.html#variance src ype_test.py:23:注意:考虑使用“映射”,即 值类型的协变
我尝试使用
MutableMapping
进行类型提示,但无济于事:
错误:“my_foo”的参数 1 具有不兼容的类型“dict[str, int]”; 预期“MutableMapping[str, int | float]”
你可以尝试这个,创建你自己的
dict
,你也可以使用数据类。此代码片段应该可以解决问题
from typing import TypedDict, Union
class MyDict(TypedDict, total=False):
some_int: int
the_int: int
the_float: float
def my_foo(x: MyDict, some_condition: bool) -> None:
if some_condition:
x["the_int"] = 1
else:
x["the_float"] = 1.0
my_dict: MyDict = {"some_int": 2}
my_foo(my_dict, True)
测试结果
mypy ol.py
Success: no issues found in 1 source file