Skip to content

Reject Self in type parameter bounds - #22074

Closed
Madin-H23 wants to merge 1 commit into
python:masterfrom
Madin-H23:fix/self-pep695-bound
Closed

Madin-H23 wants to merge 1 commit into
python:masterfrom
Madin-H23:fix/self-pep695-bound

Conversation

@Madin-H23

Copy link
Copy Markdown

Fixes #21960

Rejects Self used as the bound of a type parameter, in both PEP 695 syntax and legacy TypeVar(bound=...) declarations, by reusing the existing prohibit_self_type mechanism in semantic analysis:

  • analyze_type_param now analyzes a PEP 695 upper bound with prohibit_self_type="a type variable bound". Class-level bounds previously hit the existing "only allowed in annotations within class definition" check; they now get the more precise new message.
  • The legacy bound= path passes the same context through get_typevarlike_argument and expr_to_analyzed_type (new pass-through parameters), so TypeVar("T", bound=Self) inside a class body is also rejected. Module-level use was already rejected.

Notes:

  • The legacy path reports the follow-up "TypeVar bound must be a type" alongside the new error. I kept both for now; happy to fine-tune if a single error is preferred.
  • Constraints (TypeVar("T", Self, int)) and PEP 695 defaults are left unchanged — out of scope for this issue, can follow up if maintainers want those rejected too.

New cases are in testTypingSelfInvalidAsTypeParameterBound (check-selftype.test), covering in-class method-level and class-level PEP 695 bounds plus the legacy form.

PEP 673 only allows Self in annotations within a class definition.
Type variable bounds were not checked, so an in-class legacy
TypeVar(bound=Self) or a PEP 695 method-level [T: Self] was silently
accepted.

Fixes python#21960
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@Madin-H23

Copy link
Copy Markdown
Author

Closing in favor of #21967, which predates this PR by three weeks and is from the issue reporter. My apologies for the duplicate — I located it only after opening this one; searching by the issue's keywords missed it because the PR title is phrased differently. I'm leaving a couple of implementation notes from my own pass on #21967 instead.

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.

Self is not rejected when used as a PEP 695 type parameter bound

1 participant