python / python/mypy

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

Open
#21,960 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Self is only valid in the specific locations listed in PEP 673 and Mypy already rejects several invalid locations.
See: https://github.com/python/mypy/blob/ae39cdb2fba8908eeff6ec8d6b88879c62495fcc/test-data/unit/check-selftype.test#L1480

It seems one location wasn't covered: using Self as the bound (or constraint) of a PEP 695 type parameter.

To Reproduce:
from typing import Self
class Foo:
      def fails[T: Self](self: T) -> None: pass
Expected Behavior

Mypy should reject Self here with an error.

From a quick look at other type checkers: pyright and ty treat it as an invalid/generic TypeVar bound (TypeVar upper bound cannot be generic), while zuban rejects it with the same message mypy already uses elsewhere,
Self type is only allowed in annotations within class definition.

Actual Behavior

No error is reported.

Your Environment

Mypy version: https://github.com/python/mypy/commit/ae39cdb2fba8908eeff6ec8d6b88879c62495fcc
Python version: 3.12

TLDR; originally spotted while working on #21928 See: https://github.com/python/mypy/pull/21928#issuecomment-5557910054

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with test-data/unit/check-selftype.test around line 1480 and reproduce the PEP 695 example from the issue. Trace the existing Self validation used for other invalid locations, then add coverage for a type parameter bound or constraint. Done means mypy reports an error for the example while existing Self tests continue to pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
72/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.