Skip to content

docs: clarify that invariant-by-default applies to legacy TypeVar syntax#21108

Merged
JelleZijlstra merged 2 commits intopython:masterfrom
nuglifeleoji:docs/clarify-generic-variance-default
Mar 30, 2026
Merged

docs: clarify that invariant-by-default applies to legacy TypeVar syntax#21108
JelleZijlstra merged 2 commits intopython:masterfrom
nuglifeleoji:docs/clarify-generic-variance-default

Conversation

@nuglifeleoji
Copy link
Copy Markdown
Contributor

@nuglifeleoji nuglifeleoji commented Mar 30, 2026

Closes #20366.

The "invariant by default" rule applies to the legacy TypeVar syntax. Under PEP 695 (class MyClass[T]: ...), mypy infers variance from usage instead. Updated the wording in common_issues.rst to make this distinction clear.

Under PEP 695 class syntax variance is inferred, not invariant by default.
Closes python#20366.

Made-with: Cursor
``TypeVar`` syntax, mypy considers all user-defined generic classes invariant
by default (see :ref:`variance-of-generics` for motivation). When using the
:pep:`695` syntax (``class MyClass[T]: ...``), variance is inferred from
usage rather than defaulting to invariant. This could lead to some unexpected
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last sentence reads oddly now, I think "this" refers to the fact that mutable sequences are invariant, which we mentioned several sentences ago. I would start a new paragraph here with something like "The fact that mutable sequences are usually invariant can lead to unexpected errors..."

@nuglifeleoji
Copy link
Copy Markdown
Contributor Author

nuglifeleoji commented Mar 30, 2026

Just fixed, thanks so much for the feedback!

@JelleZijlstra JelleZijlstra merged commit 25b210d into python:master Mar 30, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants