Mypy “Union[str, Dict[str, str]]”的索引类型“str”无效;预期类型“Union[int, slice]”

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)

abc*_*ccd 7

Mypy 期望字典具有相同的类型。使用Union模型子类型关系,但由于Dict类型是不变的,键值对必须与类型注释\xe2\x80\x94(即类型)中定义的完全Union[str, Dict[str, str]]匹配,因此 中的子类型Union不会匹配(两者都不是strDict[str, str]是有效类型)。

\n

要为不同的键定义多种类型,您应该使用TypedDict.

\n

用法如下所示:https ://mypy.readthedocs.io/en/latest/more_types.html#typeddict

\n
from 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]\n
Run Code Online (Sandbox Code Playgroud)\n