[Python] How to use Generic (higher-level) type variables in type hinting system?

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I want to write a generic class using mypy, but the type argument for the class is itself a generic type. For example:

    from typing import TypeVar, Generic, Callable

    A = TypeVar("A")
    B = TypeVar("B")
    T = TypeVar("T")


    class FunctorInstance(Generic[T]):
    def __init__(self, map: Callable[[Callable[[A], B], T[A]], T]):
    self._map = map

    def map(self, x: T[A], f: Callable[[A], B]) -> T:
    return self._map(f, x)


    When I try to call mypy in the definition above I get an error:

    $ mypy typeclasses.py
    typeclasses.py:9: error: Type variable "T" used with arguments
    typeclasses.py:12: error: Type variable "T" used with arguments


    I tried adding constraints to the T TypeVar's definition but failed to make this work. Is it possible to do this?

    Continue reading...

Compartilhe esta Página