生成器函数的 return 类型提示是什么?
What is the return type hint of a generator function?
我正在尝试为生成器函数编写 :rtype:
类型提示。 returns 是什么类型呢?
例如,假设我有这个生成字符串的函数:
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
return 类型不仅仅是一个字符串,它还是某种可迭代的字符串?所以我不能只写:rtype: str
。正确的提示是什么?
从 Python 3.9 开始,您可以使用 collections.abc
中的 Generator[YieldType, SendType, ReturnType]
泛型来注释生成器。例如:
from collections.abc import Generator
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
在 Python 的早期版本中,您可以从 typing
模块导入 Generator
class。或者,可以使用 typing
中的 Iterable[YieldType]
或 Iterator[YieldType]
。
Generator[str, None, None]
或 Iterator[str]
我正在尝试为生成器函数编写 :rtype:
类型提示。 returns 是什么类型呢?
例如,假设我有这个生成字符串的函数:
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
return 类型不仅仅是一个字符串,它还是某种可迭代的字符串?所以我不能只写:rtype: str
。正确的提示是什么?
从 Python 3.9 开始,您可以使用 collections.abc
中的 Generator[YieldType, SendType, ReturnType]
泛型来注释生成器。例如:
from collections.abc import Generator
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
在 Python 的早期版本中,您可以从 typing
模块导入 Generator
class。或者,可以使用 typing
中的 Iterable[YieldType]
或 Iterator[YieldType]
。
Generator[str, None, None]
或 Iterator[str]