Closed
Description
I think this might be best explained with an example.
from typing import Union, List
class A: pass
class B: pass
class Base:
variable1 : List[Union[A, B]] = []
variable2 : List[Union[A, B]] = []
class Derived(Base):
variable1 = [A()]
variable2 = variable1
Here is the output of mypy test.py
:
test.py:12: error: Incompatible types in assignment (expression has type "List[A]", base class "Base" defined the type as "List[Union[A, B]]")
test.py:12: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:12: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)
The error is on the last line. The complaint is that variable1
is of type List[A]
, and so it cannot be assigned to variable2
. At first, this seems reasonable, but notice that the type of variable1
is explicitly defined to be List[Union[A, B]]
in the superclass. More interesting still is that the previous line, line 11, is accepted just fine.
I believe Derived types should inherit their superclass types if possible before resorting to a type inference.
Debug information:
MyPy Version: 0.931
Python Version: 3.9.2
Operating System: Debian 11
Linux Version: 5.14
And also a real world example of this.