为什么两种类型的并集列表不扩展为这两种类型列表的并集



在组合ListUnion类型时,我在mypy方面遇到了一些困难。我现在知道答案了,但我想在这里记录我的发现。问题是:为什么两种类型的并集列表不扩展为这两种类型列表的并集?那么,为什么下面的两个别名RepeatedDataType1RepeatedDataType2不等价呢?

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]]

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

以下代码演示了该问题:

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]]")

最新更新