将内置字典类型转换为 TypedDict

Ric*_*ica 4 python type-hinting mypy python-typing

我有这样的东西(非常简单):

# mymodule.py

from typing import TypedDict, cast

D=TypedDict('D', {'x':int, 'y':int})
d = {}
d['x']=1
d['y']=2
d = cast(D, d)
Run Code Online (Sandbox Code Playgroud)

但 mypy 抱怨道:

mymodule.py:9: error: Incompatible types in assignment (expression has type "D", variable has type "Dict[str, int]") Found 1 error in 1 file (checked 1 source file)

将普通字典转换为子类型不应该是有效的吗TypedDict?如果不是,“构建”字典然后声明其类型的正确方法是什么?

请注意,这是非常简单的;实际上,字典是根据比上面给出的更复杂的算法构建的。

更新:即使我更改变量名称而不是尝试转换类型,问题似乎仍然存在。

# mymodule.py

from typing import TypedDict, cast

D=TypedDict('D', {'x':int, 'y':int})
d = {}
d['x']=1
d['y']=2
dd: D = d
Run Code Online (Sandbox Code Playgroud)

error: Incompatible types in assignment (expression has type "Dict[str, int]", variable has type "D") Found 1 error in 1 file (checked 1 source file)

Mis*_*agi 5

在分配初始字典之前对其进行类型转换:

from typing import TypeDict, cast

D = TypedDict('D', {'x':int, 'y':int})
d = cast(D, {})
d['x']=1
d['y']=2
Run Code Online (Sandbox Code Playgroud)

这确保变量d被直接推断为“a D”。否则,推理会立即将变量锁定d为 a Dict[..., ...],以后无法更改。