多态函数的功能注释

问题描述

我有一个多态函数,该函数会重复传递给它的任何对象作为参数(类似于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中获得相同的结果?

解决方法

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

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