Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the second and third type parameters to typing.Generator mean?

Writing the following code

def a(n: int):
    for i in range(n):
        yield i

b = a(3)

then asking PyCharm to add type hint to variable b turns the variable declaration into

b: Generator[int, Any, None] = a(3)

What do the Any and None represent? Why does Generator take those type parameters?

like image 768
Ivan Avatar asked Sep 10 '25 14:09

Ivan


1 Answers

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.

like image 142
user2357112 supports Monica Avatar answered Sep 13 '25 03:09

user2357112 supports Monica