【问题标题】:How to use Generic (higher-level) type variables in type hinting system?如何在类型提示系统中使用通用(高级)类型变量?
【发布时间】:2019-06-04 16:44:52
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      returnsnow provides 一些第三方对 HKT 的支持。

      从他们的文档中复制一个 sn-p

      >>> 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)
      

      【讨论】:

        猜你喜欢
        • 2019-03-04
        • 2022-01-17
        • 1970-01-01
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        • 2019-03-21
        • 2020-05-14
        • 1970-01-01
        相关资源
        最近更新 更多