python - 将构建的字典类型转换为 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
被直接推断为“a D
”。否则,推理会立即将变量锁定d
为 a Dict[..., ...]
,以后无法更改。
推荐阅读
- c - avr-gcc:调用 ISR 后跳转到任意地址
- linux - How to use exec syscall in linux assembler
- java - Java json get value from directory
- python - Search google contact using People Api v3?
- python - What is the little box with an A in pyqtgraph/PyQt Viewbox with a little box and an A inside and how to get rid of it?
- relational-algebra - How to select multiple attributes along with grouping operation in Relational Algebra Queries?
- wordpress - WordPress website's index.php show unusual code
- function - Creating an automatic and self-generating weekday data entry sheet in google sheets
- python - Python 不会运行?
- python - 为什么它只返回没有任何数据的csv文件?