繁体   English   中英

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

[英]Mypy: How should I type a dict that has strings as keys and the values can be either strings or lists of strings?

我正在使用 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')我认为 TypeDict评论中以及https://stackoverflow.com/a/62862029/692695中建议的方法是通往 go 的方法,因此将该方法标记为解决方案。

请参阅类似问题: 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')

笔记:

除非您使用的是 Python 3.8 或更高版本(其中TypedDict在标准库类型模块中可用),否则您需要使用 pip 安装 typing_extensions 以使用 TypedDict


而且,当然,您可以使用Any

Mytype = Dict[str, Any]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM