[Python] Subclassing a generic class with constrained type variable in Python 3.12+ without...

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to subclass a generic class that is using a constrained type variable. This is fairly easy with pre-3.12 syntax as shown in this minimal example:

    from typing import Generic, TypeVar

    T = TypeVar("T", int, float)

    class Base(Generic[T]):
    pass

    class Sub(Base[T]):
    pass


    But I am struggling with writing this in the Python 3.12 syntax. I cannot find a way to not have to specify T: (int, float) in the Sub class as well. Below is another minimal example which passes mypy check (version 1.15.0).

    class Base[T: (int, float)]:
    pass

    class Sub[T: (int, float)](Base[T]):
    pass


    But when I change the subclass definition to class Sub[T](Base[T]):, mypy returns error: Type variable "T" not valid as type argument value for "Base" [type-var]. I would expect such definition to be meaningful and I find it unfortunate that I have to define the constraints again, especially when the classes can be in different files and subclassed multiple times.

    Am I missing something or is this not fully doable in pure Python 3.12+ syntax?

    Continue reading...

Compartilhe esta Página