生成器函数的返回类型提示是什么?

Jea*_*ett 27 python yield generator type-hinting python-2.7

我正在尝试:rtype:为生成器函数编写类型提示.它返回的类型是什么?

例如,假设我有这个函数产生字符串:

def read_text_file(fn):
    """
    Yields the lines of the text file one by one.
    :param fn: Path of text file to read.
    :type fn: str
    :rtype: ???????????????? <======================= what goes here?
    """
    with open(fn, 'rt') as text_file:
        for line in text_file:
            yield line
Run Code Online (Sandbox Code Playgroud)

返回类型不只是一个字符串,它是某种可迭代的字符串?所以我不能写:rtype: str.什么是正确的提示?

Eug*_*ash 26

注释生成器的泛型类型Generator[yield_type, send_type, return_type]typing模块提供:

def echo_round() -> Generator[int, float, str]:
    res = yield
    while res:
        res = yield round(res)
    return 'OK'
Run Code Online (Sandbox Code Playgroud)

或者你可以使用Iterable[YieldType]Iterator[YieldType].

  • @TimokKhan 第一个没有值的 `yield` 将 `None` 返回给调用者,并将相同的值分配给 `res`。如果再次调用,调用者会得到一个 `StopIteration` 异常。但是,如果调用者向生成器发送一个值,它会被分配给 `res` 并在四舍五入后产生。`res` 再次变为 `None`。只要用户发送输入,生成器就会不断生成四舍五入的值;它在没有输入的情况下调用后立即停止。见 https://replit.com/@socialguy/generator#main.py (3认同)
  • @DanielLavedoniodeLima 我猜想,“Iterable”更通用,而“Iterator”表示结果只能迭代一次。 (2认同)

ari*_*tll 22

发电机

Generator[str, None, None] 要么 Iterator[str]

  • 既然Python 3.9支持更复杂的类型提示,有新的答案吗? (8认同)

Dav*_*son 12

IteratorGenerator...相比

文档定义为“实现...和方法collections.abc.Generator的生成器类的 ABC ”。send()throw()close()

所以我使用collections.abc.Iterator[ReturnType]“普通”生成器,并保留用于我实现了//的collections.abc.Generator情况。send()throw()close()