我有这样的东西(非常简化):
# 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)
答案 0 :(得分:1)
在构建之前对初始字典进行类型转换:
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
锁定为 Dict[..., ...]
。
答案 1 :(得分:1)
一个解决方案似乎是在执行类型转换时使用一个新的变量名:
# mymodule.py
from typing import TypedDict, cast
D=TypedDict('D', {'x':int, 'y':int})
d = {}
d['x']=1
d['y']=2
dd: D = cast(D, d)
我想这会强制执行使用新变量名称的最佳实践,以便向读者表明从现在开始密钥不会改变。这对我来说似乎有点过分,但我可以理解为什么类型检查器以这种方式处理事情通常是有利的。编辑:接受的答案是更好的方法!