将内置字典类型转换为 TypedDict
type casting a built-up dictionary to a 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)
在分配初始字典之前对其进行类型转换:
from typing import TypeDict, cast
D = TypedDict('D', {'x':int, 'y':int})
d = cast(D, {})
d['x']=1
d['y']=2
这确保变量d
被直接推断为“aD
”。否则,推理会立即将变量 d
锁定为 Dict[..., ...]
,以后无法更改。
一个解决方案似乎是在执行类型转换时使用新的变量名:
# 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)
我想这会在向 reader 表示密钥从现在开始不会更改时强制执行使用新变量名的最佳实践。这对我来说似乎有点过分,但我可以理解为什么类型检查器通常以这种方式处理事情是有利的。编辑:接受的答案是更好的方法!
我有这样的东西(非常简单):
# 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)
在分配初始字典之前对其进行类型转换:
from typing import TypeDict, cast
D = TypedDict('D', {'x':int, 'y':int})
d = cast(D, {})
d['x']=1
d['y']=2
这确保变量d
被直接推断为“aD
”。否则,推理会立即将变量 d
锁定为 Dict[..., ...]
,以后无法更改。
一个解决方案似乎是在执行类型转换时使用新的变量名:
# 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)
我想这会在向 reader 表示密钥从现在开始不会更改时强制执行使用新变量名的最佳实践。这对我来说似乎有点过分,但我可以理解为什么类型检查器通常以这种方式处理事情是有利的。编辑:接受的答案是更好的方法!