What is the return type hint of a generator function?

Question:

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?

Answers:

As of Python 3.9, you can annotate a generator using the Generator[YieldType, SendType, ReturnType] generic type from collections.abc. For example:

from collections.abc import Generator

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

In earlier versions of Python you can import the Generator class from the typing module. Alternatively, Iterable[YieldType] or Iterator[YieldType] from typing can be used.

Answered By: Eugene Yarmash

Generator

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

Before python 3.9:

from typing import Generator

python 3.9 onwards:

from collections.abc import Generator
Answered By: aristotll

Comparing Iterator with Generator

The docs define collections.abc.Generator as an "ABC for generator classes that implement … the send(), throw() and close() methods".

So I use collections.abc.Iterator[ReturnType] for a ‘plain’ generator, and reserve collections.abc.Generator for cases where I have implemented send()/throw()/close().

Answered By: David Gilbertson