When is generator code executed?

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 2
2

See how, when we request the first value, the generator body runs up to and including the first yield statement. The code executes just far enough to literally yield the next value.

>>> next(g)
About to yield 4
4

When we request the next value from the generator, execution of the generator function resumes at the point it left off, and continues running until the next yield:

>>> next(g)
About to yield 6
6

After the final value has returned the next request causes the generator function to execute until it returns at the end of the function body, which in turn raises the expected StopIteration exception.

>>> next(g)
About to return
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Now that we've seen how generator execution is initiated by calls to next() and interrupted by yield statements, we can progress to placing more complex code in our generator function body.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset