python - Mypy:我应该如何键入一个以字符串作为键并且值可以是字符串或字符串列表的字典?

标签 python python-3.x mypy

我正在使用 Python 3.8.1 和 mypy 0.782。我不明白为什么 mypy 提示以下代码:

from typing import Union, List, Dict
Mytype = Union[Dict[str, str], Dict[str, List[str]]]
s: Mytype = {"x": "y", "a": ["b"]}
Mypy 在第 3 行给出以下错误:
Incompatible types in assignment (expression has type "Dict[str, Sequence[str]]", variable has type "Union[Dict[str, str], Dict[str, List[str]]]")
如果我将最后一行更改为 s: Mytype = {"a": ["b"]} mypy 没有提示。但是,当再添加一行时 s["a"].append("c")导致错误:
error: Item "str" of "Union[str, List[str]]" has no attribute "append"
上面提到的如何解释?我应该如何键入一个以字符串作为键的字典,并且值可以是字符串或字符串列表?
找到这个:https://github.com/python/mypy/issues/2984#issuecomment-285716826但仍然不完全确定为什么会发生上述情况以及我应该如何解决它。
编辑:
虽然目前还不清楚为什么建议修改 Mytype = Dict[str, Union[str, List[str]]]不能用 s['a'].append('c') 解决错误我认为在评论和 https://stackoverflow.com/a/62862029/692695 中建议的 TypeDict 方法是要走的路,所以将该方法标记为解决方案。
见类似问题:Indicating multiple value in a Dict[] for type hints ,在 Georgy 的评论中建议。

最佳答案

因为 s: Mytype不能有类型 Dict[str, str]并输入 Dict[str, List[str]]同时。你可以像这样做你想做的事:

    Mytype = Dict[str, Union[str, List[str]]]
但也许是问题,因为 Dict是不变的

您可以使用 TypedDict ,但只需要一组固定的字符串键:
from typing import List, TypedDict

Mytype = TypedDict('Mytype', {'x': str, 'a': List[str]})
s: Mytype = {"x": "y", "a": ["b"]}

s['a'].append('c')
笔记:

Unless you are on Python 3.8 or newer (where TypedDict is available in standard library typing module) you need to install typing_extensions using pip to use TypedDict



而且,当然,您可以使用 Any :
Mytype = Dict[str, Any]

关于python - Mypy:我应该如何键入一个以字符串作为键并且值可以是字符串或字符串列表的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861810/

相关文章:

python - while循环不会停止

python - 尝试理解 .strip

python - 尝试使用正则表达式捕获特定模式 (Python 3.4)

python-3.x - 让 mypy 警告不同类型变量的相等性检查

python - Python 中 mypy 的依赖类型和多态性

python-3.x - Mypy 提示明显的 bool 表达式违反了 [no-any-return] 规则

python - 谷歌阻止 Selenium Webdriver

python - 这两种将元组附加到列表的方法有什么区别

python - 在 Windows 上为 SQLite 使用 spatialite 扩展

python - @staticmethod 或类外函数?