【问题标题】:Mypy Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"Mypy “Union[str, Dict[str, str]]”的索引类型“str”无效;预期类型“Union [int, slice]”
【发布时间】:2021-11-03 11:34:36
【问题描述】:

为什么我会收到错误消息?我已经正确添加了类型,对吧?

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 你能解释一下永远为真的 if 条件(在我的情况下)如何消除错误吗?

标签: python mypy python-typing


【解决方案1】:

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]

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 2020-07-21
    • 1970-01-01
    • 2017-11-12
    • 2021-04-24
    • 2021-11-07
    • 2022-10-12
    • 2015-05-23
    • 2020-02-09
    相关资源
    最近更新 更多