Jak*_*ake 5 python mypy python-typing
为什么我会收到错误消息?我已经正确添加了类型,对吗?
Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"
Run Code Online (Sandbox Code Playgroud)
代码
from typing import List, Dict, Union
d = {"1": 1, "2": 2}
listsOfDicts: List[Dict[str, Union[str, Dict[str, str]]]] = [
{"a": "1", "b": {"c": "1"}},
{"a": "2", "b": {"c": "2"}},
]
[d[i["b"]["c"]] for i in listsOfDicts]
Run Code Online (Sandbox Code Playgroud)
Mypy 期望字典具有相同的类型。使用Union模型子类型关系,但由于Dict类型是不变的,键值对必须与类型注释\xe2\x80\x94(即类型)中定义的完全Union[str, Dict[str, str]]匹配,因此 中的子类型Union不会匹配(两者都不是str,Dict[str, str]是有效类型)。
要为不同的键定义多种类型,您应该使用TypedDict.
用法如下所示:https ://mypy.readthedocs.io/en/latest/more_types.html#typeddict。
\nfrom typing import List, Dict, Union, TypedDict\n\nd = {"1": 1, "2": 2}\n\ndictType = TypedDict(\'dictType\', {\'a\': str, \'b\': Dict[str, str]})\n\nlistsOfDicts: List[dictType] = [\n {"a": "1", "b": {"c": "1"}},\n {"a": "2", "b": {"c": "2"}},\n]\n\n[d[i["b"]["c"]] for i in listsOfDicts]\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7641 次 |
| 最近记录: |