Raf*_*ini 8 python type-hinting higher-kinded-types mypy 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)
Run Code Online (Sandbox Code Playgroud)
当我尝试在上面的定义中调用 mypy 时,出现错误:
$ mypy typeclasses.py
typeclasses.py:9: error: Type variable "T" used with arguments
typeclasses.py:12: error: Type variable "T" used with arguments
Run Code Online (Sandbox Code Playgroud)
我尝试在T TypeVar's 定义中添加约束,但未能完成这项工作。是否有可能做到这一点?
从他们的文档中复制片段
>>> 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]:
... ...
Run Code Online (Sandbox Code Playgroud)
你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)
Run Code Online (Sandbox Code Playgroud)