The second and third type parameters represent the type that the generator's send
takes, and the type that the generator returns.
send
is a feature introduced way back in Python 2.5 as part of PEP 342, which extended generators to work as coroutines. In PEP 342, yield
becomes an expression, and send
is like next
, but specifying a value for the yield
expression the generator is suspended at. (If the generator is suspended at the beginning rather than at a yield
, a non-None value cannot be sent into it.) Looking at the example in the typing.Generator
docs:
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
this generator takes floats in send
, and returns the rounded value of the send
argument.
Generator return values were introduced in Python 3.3 as part of PEP 380, as part of subgenerator delegation support. Before PEP 380, it was very awkward to divide a generator into multiple functions, in part because subgenerators had no mechanism like return
to communicate results back to their caller. With PEP 380, a generator can return
a value, which will be used as the value of a yield from
expression that yields from the generator. In the typing.Generator
documentation example, echo_round
returns a string.