Sub topic 6
How a generator runs: pausing, resuming and finishing
This chapter assumes you can write a generator function with yield and that you know how next() and StopIteration work in the iterator protocol. Here you will trace what happens inside a generator from the moment you call it until it is finished. You will also see the edge cases that surprise people.
Calling a generator function does not run it
A generator function looks like a normal function, but a call to it does not execute the body. The call builds a generator object and returns it. The body starts only when something asks for the first value.
def demo():
print("start")
yield 1
print("middle")
yield 2
print("end")
gen = demo()
print("created")
print(next(gen))
print(next(gen))
try:
next(gen)
except StopIteration:
print("stopped")This prints:
created
start
1
middle
2
end
stoppedFollow the order of the output:
demo()prints nothing. The generator is created and waits.- The first
next(gen)runs the body from the top until it reachesyield 1. That printsstart. The value1goes back to the caller, and the generator pauses. - The second
next(gen)resumes right afteryield 1. It printsmiddle, then pauses atyield 2. - The third
next(gen)resumes afteryield 2. It printsend, runs off the end of the body, and Python raisesStopIterationfor you.
A yield is therefore a pause point that hands one value to the caller. The generator keeps its place until the next request.
The four states of a generator
At any moment a generator is in one of four states. The inspect module reports the state with getgeneratorstate.
| State | Meaning |
|---|---|
| `GEN_CREATED` | The object exists, but the body has not started. |
| `GEN_RUNNING` | The body is executing right now. |
| `GEN_SUSPENDED` | The body is paused at a `yield`. |
| `GEN_CLOSED` | The body has finished, raised an exception, or been closed. |
You can watch the states change:
import inspect
def gen():
yield 1
g = gen()
print(inspect.getgeneratorstate(g)) # GEN_CREATED
next(g)
print(inspect.getgeneratorstate(g)) # GEN_SUSPENDED
try:
next(g)
except StopIteration:
pass
print(inspect.getgeneratorstate(g)) # GEN_CLOSEDNotice that after the first next() the generator is suspended, not finished. Even after the last yield has run, the generator is still suspended. It becomes closed only when a later next() lets the body reach its end.
What is preserved while paused
A paused generator keeps its whole execution frame. That includes local variables, the loop position, and the position of the current instruction. A normal function loses all of this when it returns. A generator keeps it until it closes.
def counter(limit):
n = 0
while n < limit:
n += 1
yield n
c = counter(3)
print(next(c)) # 1
print(next(c)) # 2
print(next(c)) # 3The variables n and limit live inside the suspended frame between calls. Two generator objects made from the same function have separate frames, so they do not share state:
a = counter(3)
b = counter(3)
print(next(a), next(a)) # 1 2
print(next(b)) # 1This is the property that lets a generator replace the manual self.current bookkeeping in a hand-written iterator class.
Finishing: return, end of body, and StopIteration
A generator finishes in one of three ways.
- The body runs off the end. Python raises
StopIterationto the caller. - A
returnstatement runs. The effect is the same. A barereturnis a clean early exit. - An exception escapes the body. The exception propagates to the caller, and the generator is closed.
Early exit with return is often the clearest way to stop:
def take_until_negative(values):
for v in values:
if v < 0:
return
yield v
print(list(take_until_negative([3, 1, -1, 5]))) # [3, 1]The 5 is never produced, because the generator closed at -1.
A for loop, list(), and other consumers catch StopIteration for you. That is why you rarely see it unless you call next() yourself.
A closed generator stays closed
Once a generator is closed, it never restarts. Every further next() raises StopIteration immediately, and the body does not run again.
def one():
yield "only"
g = one()
print(list(g)) # ['only']
print(list(g)) # []
print(next(g, "no more")) # no moreThe two-argument form next(g, default) returns the default instead of raising, which is convenient for a single peek at a possibly empty stream. To get fresh values, call the generator function again to make a new generator object.
Exceptions close the generator
If the body raises an exception, the caller sees it. The generator is then closed, even though the code after the raise never ran.
def risky():
yield 1
raise ValueError("boom")
yield 2
g = risky()
print(next(g)) # 1
try:
next(g)
except ValueError as e:
print("caught", e) # caught boom
try:
next(g)
except StopIteration:
print("finished") # finishedThe yield 2 never happens. The generator is not left in a half-working state. After the failure it behaves like any other finished generator.
Edge cases
Raising StopIteration inside a generator body
You might expect raise StopIteration to be a valid way to end a generator. Since Python 3.7 (PEP 479) it is not. A StopIteration that escapes a generator body is converted into a RuntimeError. Without this rule, a stray StopIteration from a next() call deep in your code would silently end the generator early and hide a bug.
def bad():
yield 1
raise StopIteration
g = bad()
print(next(g)) # 1
try:
next(g)
except RuntimeError as e:
print(e) # generator raised StopIterationUse return to end a generator. Only an iterator class's __next__ method should raise StopIteration directly.
A generator cannot resume itself
If code inside a generator tries to advance that same generator, Python refuses. The generator is in the running state, so it cannot be resumed again.
def f():
yield next(g)
g = f()
try:
next(g)
except ValueError as e:
print(e) # generator already executingThis is rare in practice. It can appear by accident with callbacks that end up calling next() on the generator that invoked them.
Stopping early leaves the generator suspended
Breaking out of a for loop does not finish the generator. It stays suspended at its last yield. This matters when the body holds a resource, such as an open file. A try/finally block inside the generator runs its finally part when the generator is closed.
def reader():
try:
yield 1
yield 2
finally:
print("cleanup")
for x in reader():
print(x)
breakThis prints 1 and then cleanup. In CPython the generator is destroyed as soon as the loop drops its reference, and destruction closes it, which runs the finally block. The language does not guarantee that timing on every Python implementation. If cleanup must happen at a known moment, keep a reference to the generator and call close() yourself. A later chapter covers close().
Arguments are bound when you call, the body runs later
Because the body is deferred, any error in it appears at the first next(), not at the call. A generator function that fails on bad input will not complain until you iterate.
def first_n(items, n):
if n < 0:
raise ValueError("n must be non-negative")
for item in items[:n]:
yield item
g = first_n([1, 2, 3], -1) # no error yet
print("created")
try:
next(g)
except ValueError as e:
print(e) # n must be non-negativeIf you want eager validation, split the function in two. An ordinary function checks the arguments, then returns an inner generator:
def first_n(items, n):
if n < 0:
raise ValueError("n must be non-negative")
def run():
for item in items[:n]:
yield item
return run()Now first_n([1, 2, 3], -1) raises at the call.
Debugging checklist
When a generator behaves unexpectedly, check these points in order:
- Did you call the generator function? Without the call you hold the function, not a generator.
- Has the generator already been consumed? A closed generator yields nothing more.
- Is an error hidden until the first
next()because the body is deferred? - Is a
StopIterationescaping the body and turning into aRuntimeError? - Is something holding a suspended generator open that should have been closed?
Exercise
What does this program print, and in what order? def steps(): print("a") yield 1 print("b") yield 2 print("c") g = steps() print("x") print(next(g)) print("y") print(list(g))
Show answer
It prints x, a, 1, y, b, c, [2], each on its own line. Creating the generator prints nothing, so "x" comes first. The first next() runs to the first yield, printing "a" and returning 1. After "y", list(g) resumes the generator: it prints "b", collects 2, then prints "c" as the body ends and StopIteration stops list. The list contains only [2] because the value 1 was already consumed.
Exercise
A generator is created and one value is taken from it with next(). What does inspect.getgeneratorstate report, and which call finally changes it to GEN_CLOSED?
Show answer
It reports GENSUSPENDED, because the body is paused at a yield and has not finished. The state becomes GENCLOSED when the body ends (a later next() lets it reach the end or a return, which raises StopIteration), when an exception escapes it, or when close() is called.