【问题标题】:Can mypy detect bad TypedDict return types?mypy 可以检测到错误的 TypedDict 返回类型吗?
【发布时间】: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


【解决方案1】:

事实证明 mypy 检测到这一点没有问题,但我错误地认为在 venv 中键入调用 mypy 会在 venv 中使用它们的 mypy。我必须输入 python3 -m mypy 才能运行正确的可执行文件。

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多