我试图为生成器函数编写: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
。什么是正确的暗示?
答案 0 :(得分:16)
Generator[str, None, None]
或Iterator[str]
答案 1 :(得分:15)
注释生成器的泛型类型是typing
模块提供的Generator[yield_type, send_type, return_type]
:
def echo_round() -> Generator[int, float, str]:
res = yield
while res:
res = yield round(res)
return 'OK'
或者,您可以使用Iterable[YieldType]
或Iterator[YieldType]
。