Closed
Description
Here is a reproduction snippet:
from typing import List, Sequence, cast
class A:
pass
class B1(A):
pass
class B2(A):
pass
# ok
list1: List[A] = [A()] * 10
# ok
list2: List[A] = [B1()] * 10
list2 += [B2()] * 10
# error!
list3: List[A] = [B1()] * 10 + [B2()] * 10
# error!
seq3: Sequence[A] = [B1()] * 10 + [B2()] * 10
# ok, but looks weird
list4: List[A] = [cast(A, B1())] * 10 + [B2()] * 10
Error report looks like this:
test.py:22: error: Incompatible types in assignment (expression has type "List[B1]", variable has type "List[A]")
test.py:22: error: List item 0 has incompatible type "B2"; expected "B1"
test.py:24: error: List item 0 has incompatible type "B2"; expected "B1"
The covariance of Sequence
helps eliminate the first error. But I can never add two lists of objects of different classes without existing annotation, even the classes have same base.
In my opinion, cast
takes place when downcasting is necessary. So it should not be used in this way.