Error on generic NamedTuple method that uses constrained type parameter
Open
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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