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].
Dav*_*son 12
Iterator与Generator...相比
文档定义为“实现...和方法collections.abc.Generator的生成器类的 ABC ”。send()throw()close()
所以我使用collections.abc.Iterator[ReturnType]“普通”生成器,并保留用于我实现了//的collections.abc.Generator情况。send()throw()close()
| 归档时间: |
|
| 查看次数: |
7971 次 |
| 最近记录: |