Mypy: "str"是无效的索引类型,应该是“Union[int, slice]”,而不是“Union[str, Dict[str, str]]”。

5
为什么会出现错误?我已经正确添加了类型,对吗?
Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"

代码

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]

[d[i["b"]["c"]] for i in listsOfDicts if isinstance(i["b"], dict)] - alex_noname
1个回答

7
Mypy期望字典具有相同的类型。使用Union建模子类型关系,但由于Dict类型是不变的,键-值对必须完全匹配类型注释中定义的内容,即类型Union[str, Dict[str, str]],因此Union中的子类型不会被匹配(strDict [str,str] 都不是合法类型)。
要为不同的键定义多个类型,请使用TypedDict
如在此处所见:https://mypy.readthedocs.io/en/latest/more_types.html#typeddict
from typing import List, Dict, Union, TypedDict

d = {"1": 1, "2": 2}

dictType = TypedDict('dictType', {'a': str, 'b': Dict[str, str]})

listsOfDicts: List[dictType] = [
    {"a": "1", "b": {"c": "1"}},
    {"a": "2", "b": {"c": "2"}},
]

[d[i["b"]["c"]] for i in listsOfDicts]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接