【问题标题】:functional annotation of polymorphic functions多态函数的功能注释
【发布时间】:2020-08-25 20:13:14
【问题描述】:

假设我有一个多态函数,它重复作为参数传递给它的任何对象(类似于 Python 标准库中的 itertools.repeat):

def repeat(i):
    while True:
        yield i

如何编写函数注释来说明这是一个多态函数?

让我说清楚,我知道一种可能性是写:

from typing import Any, Iterable


def repeat(i: Any) -> Iterable[Any]:
    while True:
        yield i

然而,这个解决方案是模棱两可的,因为它适用于以下两种情况:

repeat(i: Apples) -> Iterator[Apples]:

repeat(i: Apples) -> Iterator[Oranges]:

我想要一个真正反映函数接受任何类型但它返回一个迭代器的解决方案,该迭代器产生用于调用函数的相同类型。

作为 Haskell 的一个例子,这可以使用类型变量来解决,Haskell 中的函数类型就是:

repeat :: a -> [a]

其中a 是一个类型变量。我怎么会在 Python 中得到相同的结果?

【问题讨论】:

  • 使用typing.TypeVar

标签: python annotations polymorphism


【解决方案1】:

有一个非常相似的example in the Python docs 使用TypeVar

def repeat(x: T, n: int) -> Sequence[T]:
    """Return a list containing n references to x."""
    return [x]*n

在哪里使用T = TypeVar('T') # Can be anything。所以你可以适应这个:

from typing import Iterable, TypeVar

T = TypeVar('T')

def repeat(i: T) -> Iterable[T]:
    while True:
        yield i

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多