为什么两种类型的联合列表不能扩展到这两种类型的列表的联合?
当组合list
和Union
类型时,我一直在用mypy
努力挣扎。我现在知道答案,但想在这里记录我的发现。问题是:为什么两种类型的联合列表不扩展到这两种类型的列表的结合?那么,为什么两个别名repoteddatatype1
和repoteddatatype2
下面不等于?
from typing import List, Union
DataType = Union[str, int]
RepeatedDataType1 = List[DataType]
# (type alias) RepeatedDataType1: Type[List[str | int]]
RepeatedDataType2 = Union[List[str], List[int]]
# (type alias) RepeatedDataType2: Type[List[str]] | Type[List[int]]
I have been struggling a bit with mypy
when combining List
and Union
types. I know the answer now, but would like to document my findings on here. The question is: Why does a list of a union of two types not expand to union of lists of these two types? So, why are the two aliases RepeatedDataType1
and RepeatedDataType2
below not equivalent?
from typing import List, Union
DataType = Union[str, int]
RepeatedDataType1 = List[DataType]
# (type alias) RepeatedDataType1: Type[List[str | int]]
RepeatedDataType2 = Union[List[str], List[int]]
# (type alias) RepeatedDataType2: Type[List[str]] | Type[List[int]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我花了一点时间才了解发生了什么。这个问题的答案是,这两种类型确实不同,因为两种类型的联合列表也可能包含混合类型。
以下代码证明了问题:
It took me a little time to understand what was happening. The answer to this question is that these two types are really different because a list of a union of two types can also contain mixed types.
The following code demonstrates the issue: