Search code examples
pythonpython-typingmypy

typing.Generator extract ReturnType from Generator


taking this properly typed example from the official Python docs:

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

How does one "extract" the ReturnType? Consider the following example:

def use_generator() -> str:
    # Do generator stuff, keeping this a minimal example...
    next(echo_round())
    # Finally get the return value
    val = echo_round()
    # Do something else?
    return val

The mypy error message I receive for the last line:

Incompatible return value type (got "Generator[int, float, str]", expected "str")

Solution

  • The val variable receives the generator object from echo_round(). The val value stays a generator type because the code does nothing with the value, and therefore is returned as Generator[int, float, str] type. This is causing an error because use_generator() expects to return val as str type.