How to use Generic (higher-kinded) type variables in python's type hinting system?

混江龙づ霸主 提交于 2019-12-02 07:02:59

问题


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

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


回答1:


Currently, as of writing, the mypy project does not support higher-kinded types. See the following github issue:

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



来源:https://stackoverflow.com/questions/54118095/how-to-use-generic-higher-kinded-type-variables-in-pythons-type-hinting-syste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!