Nicio
Nicio

Reputation: 68

Why does a list of a union of two types not expand to a union of lists of these two types?

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

Upvotes: 1

Views: 235

Answers (1)

Nicio
Nicio

Reputation: 68

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

Upvotes: 1

Related Questions