What is the return type hint of a generator function?

36,567

Solution 1

Generator

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

Solution 2

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.

Share:
36,567

Related videos on Youtube

Jean-François Corbett
Author by

Jean-François Corbett

I'm a physicist / software enthusiast working in wind power. https://www.linkedin.com/in/jfcorbett/ I used to code on this, hooked up to our TV with a coaxial: That's color, baby!

Updated on July 08, 2022

Comments

  • Jean-François Corbett
    Jean-François Corbett almost 2 years

    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?

    • Panagiotis Simakis
      Panagiotis Simakis about 7 years
      returns a generator with strings
    • Moses Koledoye
      Moses Koledoye about 7 years
      Looks like you're not asking for a type hint but a docstring insertion for :rtype:
    • Wood
      Wood almost 5 years
      People mark as duplicate without even reading the question. Sigh...
    • Jean-François Corbett
      Jean-François Corbett almost 5 years
      @Wood Look again...
    • Wood
      Wood almost 5 years
      @Jean-FrançoisCorbett The other question asks for the type annotation. This one asks for the docstring insertion for :rtype:. They are different things.
    • Jean-François Corbett
      Jean-François Corbett almost 5 years
      @Wood Look again at who "people" is... I can assure you, I read my own question. And the other one.
    • Wood
      Wood almost 5 years
      @Jean-FrançoisCorbett It's typical in the IT community for people to solve their own problems and not share how they did it with other people. You being the author of the question should not give you the right to falsely mark it as duplicate.
    • OrenIshShalom
      OrenIshShalom about 2 years
      Note that (currently) sphinx is able to automatically extract the return type (rtype) from the corresponding type hint ...
  • Timok Khan
    Timok Khan almost 3 years
    Could somebody explain what this function echo_round do? I am lost!
  • Abhijit Sarkar
    Abhijit Sarkar almost 3 years
    @TimokKhan The first yield, without a value returns None to the caller, and assigns the same to res. If invoked again, the caller gets a StopIteration exception. However, if the caller sends a value to the generator, it is assigned to res and yielded after rounding. res becomes None again. The generator keeps producing rounded values as long as the user sends an input; it stops as soon as invoked without an input. See replit.com/@socialguy/generator#main.py
  • Timok Khan
    Timok Khan almost 3 years
    Thanks! Seeing how it is used helped a lot!
  • Nathan Dai
    Nathan Dai over 2 years
    Is there a new answer now that Python 3.9 supports more complex type hints?
  • Eugene Yarmash
    Eugene Yarmash about 2 years
    @NathanDai In Python 3.9 the syntax is basically the same, you just import the Generator class from collections.abc. See my answer for the details.
  • Daniel Lavedonio de Lima
    Daniel Lavedonio de Lima almost 2 years
    What's the difference between Iterator and Iterable when using for type hinting the yield action?
  • Eugene Yarmash
    Eugene Yarmash almost 2 years
    @DanielLavedoniodeLima I guess, Iterable is more generic, while Iterator indicates that the result can be iterated only once.