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

时间:2019-01-09 20:46:36

标签: python type-hinting mypy higher-kinded-types python-typing

假设我想使用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的定义中添加约束,但未能完成这项工作。可以这样做吗?

2 个答案:

答案 0 :(得分:1)

当前,截至撰写本文时,mypy项目不支持类型较高的类型。请参阅以下github问题:

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

答案 1 :(得分:1)

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)