【发布时间】:2020-06-10 19:14:10
【问题描述】:
我正在努力让 mypy 为我的项目提供足够全面的工作。
from typing import TypedDict
OurDict = TypedDict('OurDict', {'x': int})
bad: OurDict = {'y': 2} # mypy successfully marks wrong
good: OurDict = {'x': 2} # mypy likes this
def get_bad() -> OurDict:
return 234 # mypy successfully marks wrong
def get_good() -> OurDict:
res = {'x': 2}
return res # mypy successfully marks correct
def get_should_be_bad() -> OurDict:
return {'hello': 2, 'world': 1} # mypy fails to see a problem
似乎 mypy 可以在声明内联时检测字典是否符合类型定义,但在检查函数返回值时,它只检查返回值是某种字典,而不是所需的类型。这只是设计的限制还是我做错了什么?
【问题讨论】:
-
使用 Python 3.8 和
mypy==0.761,我在get_should_be_bad的正文中得到了error: Extra keys ('hello', 'world') for TypedDict "OurDict"。 -
谢谢,原来是版本问题。我在 python 3.8 venv 中运行 mypy,我认为它会在 venv 中使用 mypy,但结果证明它使用的是系统 mypy。当我输入 python -m mypy 时,它工作正常。我应该删除这篇文章吗?
标签: pycharm static-analysis mypy python-3.8