Please include full self-contained examples of code showing the error you are experiencing. It makes helping you so much easier
I suppose you were writing something like
x = [A(), A()]
y = [B(), B()]
z = x + y # error here
right? Your problem here is that the type of x is List[A], and the type of y is List[B]. Because the List type is invariant this is rejected. You can fix it by adding # type: List[A] to the assignment to y.
Actually x + y would be safe if the inferred type of the result was List[A]. There currently is no way to represent this in the type system, though. We could probably write a type system plugin to support this if this seems to be a common enough issue.
w = [A(), A()]
x = [B(), B()]
y = [C(), C()]
z = [D(), D()]
Now, if I add any combination of different lists I will get the mypy error error: Unsupported operand types for + (List[X] and List[Y]) :
new_list = w + x # should be type: List[A]
new_list = w + y # should be type: List[A]
new_list = w + z # should be type: List[A]
new_list = x + y # should be type: List[A]
new_list = x + z # should be type: List[B]
new_list = y + z # should be type: List[A]
i.e., The highest common Parent class should become the type of the new list
@henryJack Without writing a mypy plugin your only type-safe way to get this to work is to add explicit declarations so that all lists have type List[A].
Activity
gvanrossum commented on Sep 7, 2017
Please include full self-contained examples of code showing the error you are experiencing. It makes helping you so much easier
I suppose you were writing something like
right? Your problem here is that the type of x is List[A], and the type of y is List[B]. Because the List type is invariant this is rejected. You can fix it by adding # type: List[A] to the assignment to y.
JukkaL commented on Sep 7, 2017
Actually x + y would be safe if the inferred type of the result was List[A]. There currently is no way to represent this in the type system, though. We could probably write a type system plugin to support this if this seems to be a common enough issue.
henryJack commented on Sep 7, 2017
Yes, sorry. I'll try to be more explicit:
If I declare the following classes:
Then I prepare some pure lists:
Now, if I add any combination of different lists I will get the mypy error error: Unsupported operand types for + (List[X] and List[Y]) :
i.e., The highest common Parent class should become the type of the new list
henryJack commented on Sep 7, 2017
Then of course,
Because the highest common parent class is now A
gvanrossum commented on Sep 7, 2017
@henryJack Without writing a mypy plugin your only type-safe way to get this to work is to add explicit declarations so that all lists have type List[A].
mokulus commented on Aug 7, 2024
This is still a problem: