为什么 `mypy` 没有检测到函数内部错误的 TypedDict 用法

Why doesn't `mypy` detect bad TypedDict usage inside a function

我有以下 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.[=16 行中完全相同的问题=]

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

怎么回事?

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

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