python / python/mypy

Error on generic NamedTuple method that uses constrained type parameter

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

Nobody has claimed this yet.

bug topic-named-tuple topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

mypy reports The erased type of self ... is not a supertype of its class for a method on a generic NamedTuple when the class uses constrained type variables.

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

Produces:

main.py:8: error: The erased type of self "tuple[str, fallback=main.Result[str]]" is not a supertype of its class "tuple[S, fallback=main.Result[S]]"  [misc]
main.py:8: error: The erased type of self "tuple[bytes, fallback=main.Result[bytes]]" is not a supertype of its class "tuple[S, fallback=main.Result[S]]"  [misc]

Version

Observed with:

mypy 2.0.0 (compiled: yes)

This came up with some generic namedtuples in urllib.parse in typeshed (python/typeshed#15726).

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 the generic NamedTuple reproducer in main.py and run it with mypy 2.0.0 to confirm the two self-erasure errors. Trace mypy's handling of generic NamedTuple methods and constrained type variables, then add a regression test showing that get_value is accepted without these errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
65/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.