代码之家  ›  专栏  ›  技术社区  ›  Rafael S. Calsaverini

如何在Python的类型提示系统中使用通用(更高级)类型变量?

  •  1
  • Rafael S. Calsaverini  · 技术社区  · 7 年前

    假设我想使用mypy编写一个泛型类,但该类的类型参数本身就是一个泛型类型。例如:

    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[B]]):
            self._map = map
    
        def map(self, x: T[A], f: Callable[[A], B]) -> T[B]:
            return self._map(f, x)
    

    当我试图在上面的定义中调用mypy时,我会得到一个错误:

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

    我尝试在 T TypeVar 的定义,但未能使其生效。可以这样做吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   juanpa.arrivillaga    7 年前

    目前,在写作时, mypy 项目不支持更高类型。请参阅以下Github问题:

    https://github.com/python/typing/issues/548

    推荐文章