为什么两种类型的联合列表不能扩展到这两种类型的列表的联合?

发布于 2025-01-19 19:44:23 字数 543 浏览 4 评论 0原文

当组合listUnion类型时,我一直在用mypy努力挣扎。我现在知道答案,但想在这里记录我的发现。问题是:为什么两种类型的联合列表不扩展到这两种类型的列表的结合?那么,为什么两个别名repoteddatatype1repoteddatatype2下面不等于?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自由如风 2025-01-26 19:44:23

我花了一点时间才了解发生了什么。这个问题的答案是,这两种类型确实不同,因为两种类型的联合列表也可能包含混合类型。

以下代码证明了问题:

repeated_data1: RepeatedDataType1 = ["a", 1]  # OK
repeated_data2: RepeatedDataType2 = ["a", 1]  # Incompatible types in assignment
# (expression has type "List[object]", variable has type "Union[List[str], List[int]]")

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:

repeated_data1: RepeatedDataType1 = ["a", 1]  # OK
repeated_data2: RepeatedDataType2 = ["a", 1]  # Incompatible types in assignment
# (expression has type "List[object]", variable has type "Union[List[str], List[int]]")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文