Skip to content

Fix false positive for constrained NamedTuple self types#21546

Open
BHUVANSH855 wants to merge 3 commits into
python:masterfrom
BHUVANSH855:fix-21453-namedtuple-constrained-typevar
Open

Fix false positive for constrained NamedTuple self types#21546
BHUVANSH855 wants to merge 3 commits into
python:masterfrom
BHUVANSH855:fix-21453-namedtuple-constrained-typevar

Conversation

@BHUVANSH855
Copy link
Copy Markdown

Fixes #21453

This PR fixes a false positive reported for methods on generic NamedTuple classes that use constrained type variables.

Example:

from typing import Generic, NamedTuple, TypeVar

S = TypeVar("S", str, bytes)

class Result(NamedTuple, Generic[S]):
    value: S

    def get_value(self) -> S:
        return self.value

Previously mypy incorrectly reported:

The erased type of self ... is not a supertype of its class ...

The issue occurred during self-type validation for tuple-backed NamedTuple types using constrained TypeVars.

This change adds a narrow special-case in the self-type checker to avoid the false positive while preserving existing subtype semantics.

Changes included:

  • Added a targeted fix in mypy/checker.py
  • Added a regression test in test-data/unit/check-selftype.test

Verification:

  • Reproduced the original issue locally
  • Added regression coverage
  • Ran python -m pytest -q mypy/test/testcheck.py -n0
  • All tests passed

@github-actions

This comment has been minimized.

@BHUVANSH855 BHUVANSH855 force-pushed the fix-21453-namedtuple-constrained-typevar branch from 87d8ebe to 613358a Compare May 27, 2026 09:30
@BHUVANSH855 BHUVANSH855 force-pushed the fix-21453-namedtuple-constrained-typevar branch from 102c263 to 2fe2202 Compare May 27, 2026 09:44
@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. ✅

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.

Error on generic NamedTuple method that uses constrained type parameter

1 participant