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

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

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

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 的定义添加约束,但未能成功。可以这样做吗?

目前,在撰写本文时,mypy 项目不支持更高种类的类型。请参阅以下 github 问题:

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

returns package now provides 一些第三方对 HKT 的支持。

从他们的文档中复制片段

>>> from returns.primitives.hkt import Kind1
>>> from returns.interfaces.container import Container1
>>> from typing import TypeVar

>>> T = TypeVar('T', bound=Container1)

>>> def to_str(arg: Kind1[T, int]) -> Kind1[T, str]:
...   ...

你的Functor会像

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], Kind1[T, A]], Kind1[T, B]]
    ):
        self._map = map

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