我正在使用 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/