What is the return type hint of a generator function?

PythonPython 2.7GeneratorYieldType Hinting

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Generator

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

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJean-Fran&#231;ois CorbettView Question on Stackoverflow
Solution 1 - PythonaristotllView Answer on Stackoverflow
Solution 2 - PythonEugene YarmashView Answer on Stackoverflow