当我运行mypy script.py --strict
时,以下代码将引发错误Argument 1 to "test" has incompatible type "Dict[str, object]"; expected "Dict[str, Union[str, int]]"
from typing import Union, Dict, Mapping
def test(person: Dict[str, Union[str, int]]) -> None:
pass
person = dict(
name='john',
age=10,
)
test(person)
编辑:
我想出一种解决此问题的方法是使用TypedDict
,如下所示:
from mypy_extensions import TypedDict
PersonDict = TypedDict('PersonDict', {
'name': str,
'age': int,
})
...
person: PersonDict = dict(
name='john',
age=10,
)
test(person)