【问题标题】:Why doesn't `mypy` detect bad TypedDict usage inside a function为什么 `mypy` 不能检测到函数内的错误 TypedDict 使用
【发布时间】:2020-06-22 07:37:50
【问题描述】:

我有以下 Python 模块:

from typing import TypedDict

class P(TypedDict):
    x: int

def return_p() -> P:
    return {'x': 5}

p = return_p()
p['abc'] = 1

def test():
    p = return_p()
    p['abc'] = 2

当我在其上运行mypy 时,它正确地抱怨p['abc']=1 行,但忽略了p['abc']=2 行中完全相同的问题。

这发生在 Windows 10 上,使用 Python 3.8 和 mypy 0.781。 Python 3.7 也会出现同样的行为(我需要从 typing_extensions 导入 TypedDict

发生了什么事?

【问题讨论】:

    标签: python mypy python-typing


    【解决方案1】:

    这是因为没有输入test()。在其签名中添加类型提示将使其正文可检查:

    def test() -> None:
        p = return_p()
        p['abc'] = 2
    

    【讨论】:

      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 2019-04-23
      • 2023-01-16
      • 2022-11-21
      • 2016-04-17
      • 1970-01-01
      相关资源
      最近更新 更多