首页 > 解决方案 > 将构建的字典类型转换为 TypedDict

问题描述

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

# 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)

但 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

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)

标签: pythontype-hintingmypypython-typing

解决方案


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

from typing import TypeDict, cast

D = TypedDict('D', {'x':int, 'y':int})
d = cast(D, {})
d['x']=1
d['y']=2

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


推荐阅读