*Memo:
mypy --strict test.py
- mypy 1.19.0
- Python 3.14.0
- Windows 11
Invariance vs covariance says mypy considers all user-defined generic classes invariant by default as shown below:
Most mutable generic collections are invariant, and mypy considers all user-defined generic classes invariant by default (see Variance of generic types for motivation). This could lead to some unexpected errors when combined with type inference. For example:
But an empty generic class is covariant against what the doc says as shown below:
class A: ...
class B(A): ...
class C(B): ...
class MyCls[T]: ...
mycls1: MyCls[A] = MyCls[B]() # No error
mycls2: MyCls[B] = MyCls[B]() # No error
mycls3: MyCls[C] = MyCls[B]() # Error