What is the return type hint of a generator function?

Jean-François Corbett picture Jean-François Corbett · Apr 27, 2017 · Viewed 16.3k times · Source

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

For example, say I have this functions which yields 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 isn't just a string, it's some kind of iterable of strings? So I can't just write :rtype: str. What's the right hint?

Answer

aristotll picture aristotll · Apr 27, 2017

Generator

Generator[str, None, None] or Iterator[str]