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

时间:2017-04-27 13:15:38

标签: python python-2.7 generator yield type-hinting

我试图为生成器函数编写: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。什么是正确的暗示?

2 个答案:

答案 0 :(得分:16)

Generator

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]