[英]Mypy: How should I type a dict that has strings as keys and the values can be either strings or lists of strings?
I am using Python 3.8.1 and mypy 0.782.我正在使用 Python 3.8.1 和 mypy 0.782。 I don't understand why mypy complains about the following code:我不明白为什么 mypy 抱怨以下代码:
from typing import Union, List, Dict
Mytype = Union[Dict[str, str], Dict[str, List[str]]]
s: Mytype = {"x": "y", "a": ["b"]}
Mypy gives the following error on line 3: Mypy 在第 3 行给出以下错误:
Incompatible types in assignment (expression has type "Dict[str, Sequence[str]]", variable has type "Union[Dict[str, str], Dict[str, List[str]]]")
If I change the last line to s: Mytype = {"a": ["b"]}
mypy doesn't complain.如果我将最后一行更改为s: Mytype = {"a": ["b"]}
mypy 不会抱怨。 However, when adding yet one more line s["a"].append("c")
leads to an error:但是,当再添加一行时s["a"].append("c")
会导致错误:
error: Item "str" of "Union[str, List[str]]" has no attribute "append"
How can the above mentioned be explained?上面提到的怎么解释? How should I type a dict that has strings as keys and the values can be either strings or lists of strings?我应该如何键入以字符串为键且值可以是字符串或字符串列表的字典?
Found this: https://github.com/python/mypy/issues/2984#issuecomment-285716826 but still not completely sure why the above mentioned happens and how should I fix it.发现这个: https://github.com/python/mypy/issues/2984#issuecomment-285716826但仍然不完全确定为什么会发生上述情况以及我应该如何解决它。
EDIT: Although it's still not clear why the suggested modification Mytype = Dict[str, Union[str, List[str]]]
does not resolve the error with s['a'].append('c')
I think the TypeDict approach suggested in the comments as well as in https://stackoverflow.com/a/62862029/692695 is the way to go, so marking that approach as a solution.编辑:虽然仍然不清楚为什么建议的修改Mytype = Dict[str, Union[str, List[str]]]
不能解决错误s['a'].append('c')
我认为 TypeDict评论中以及https://stackoverflow.com/a/62862029/692695中建议的方法是通往 go 的方法,因此将该方法标记为解决方案。
See similar question at: Indicating multiple value in a Dict[] for type hints , suggested in the comments by Georgy.请参阅类似问题: Indicating multiple value in a Dict[] for type hints ,Georgy 在评论中建议。
Because s: Mytype
cannot have type Dict[str, str]
and type Dict[str, List[str]]
at the same time.因为s: Mytype
不能同时具有类型Dict[str, str]
和类型Dict[str, List[str]]
。 You could do what you want like this:你可以像这样做你想做的事:
Mytype = Dict[str, Union[str, List[str]]]
But maybe problems, because Dict
is invariant但也许有问题,因为Dict
是不变的
Also you could useTypedDict
, but only a fixed set of string keys is expected:您也可以使用TypedDict
,但只需要一组固定的字符串键:
from typing import List, TypedDict
MyType = TypedDict('MyType', {'x': str, 'a': List[str]})
s: MyType = {"x": "y", "a": ["b"]}
s['a'].append('c')
NOTE:笔记:
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除非您使用的是 Python 3.8 或更高版本(其中TypedDict
在标准库类型模块中可用),否则您需要使用 pip 安装 typing_extensions 以使用 TypedDict
And, of course, you can use Any
:而且,当然,您可以使用Any
:
Mytype = Dict[str, Any]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.