如何在python的类型提示系统中使用泛型(高级)类型变量? [英] How to use Generic (higher-kinded) type variables in python's type hinting system?
本文介绍了如何在python的类型提示系统中使用泛型(高级)类型变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想使用mypy编写一个泛型类,但是该类的type参数本身就是一个泛型类型.例如:
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)
当我尝试在上面的定义中调用mypy时,出现错误:
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
我尝试在T
TypeVar
的定义中添加约束,但未能使此工作生效.可以这样做吗?
I tried adding constraints to the T
TypeVar
's definition but failed to make this work. Is it possible to do this?
推荐答案
当前,截至撰写本文时,mypy
项目不支持类型较高的类型.请参阅以下github问题:
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
这篇关于如何在python的类型提示系统中使用泛型(高级)类型变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文