June 2017
Beginner
352 pages
8h 39m
English
Let's take a closer look at how — and crucially when — the code in the body of our generator function is executed. To do this, we'll create a slightly more complex generator that traces its execution with good old-fashioned print statements:
>>> def gen246():... print("About to yield 2")... yield 2... print("About to yield 4")... yield 4... print("About to yield 6")... yield 6... print("About to return")...>>> g = gen246()
At this point the generator object has been created and returned, but none of the code within the body of the generator function has yet been executed. Let's make an initial call to next():
>>> next(g)About to yield 22
See how, when we request the first value, the generator body runs up ...
Read now
Unlock full access