Skip to content

Error on generic NamedTuple method that uses constrained type parameter #21453

@JelleZijlstra

Description

@JelleZijlstra

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).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions