What is the return type of the generator function?

I am trying to write a type hint :rtype:for a generator function. What is the type it returns?

For example, let's say that I have these functions that give strings:

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

The return type is not just a string, is it some sort of iterability of strings? So I can’t just write :rtype: str. What is the right hint?

+6
source share
2 answers

The general type of annotation generators is Generator[yield_type, send_type, return_type]provided by the module typing:

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

Iterable[YieldType] Iterator[YieldType].

+3

Source: https://habr.com/ru/post/1016828/


All Articles