Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions