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

我正在尝试为一个生成器函数编写一个 :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

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

48148 次浏览

As of Python 3.9, you can annotate a generator using the Generator[YieldType, SendType, ReturnType] generic type from collections.abc. For example:

from collections.abc import Generator


def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'

In earlier versions of Python you can import the Generator class from the typing module. Alternatively, Iterable[YieldType] or Iterator[YieldType] from typing can be used.

Generator

Generator[str, None, None] or Iterator[str]