mypy:对于带字符串和整数值的字典,我应该使用哪种类型

时间:2019-04-17 12:35:27

标签: python mypy python-typing

当我运行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)

0 个答案:

没有答案