Skip to content

An empty generic class is covariant even though the doc says "all user-defined generic classes invariant by default" #20366

@hyperkai

Description

@hyperkai

*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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions