Sub topic 6
How a generator runs: pausing, resuming and finishing
This chapter assumes you can write functions, use try/except, and know that iter() and next() drive an iterator. It also assumes you have seen a generator function that uses yield. Here you will learn exactly what happens at each step of a generator's life.
A call does not run the body
Calling a generator function does not execute any of its code. It creates 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")The output is:
created
start
1
middle
2
end
stoppedNotice that created prints before start. Creating the generator ran nothing.
The three states
A generator object is always in one of these states:
- Created: the object exists, but the body has not started.
- Suspended: the body ran up to a
yieldand is paused there. Local variables and the position in the code are kept. - Finished: the body ended, either by reaching the end or by a
return. The generator cannot run again.
What next() does
Each call to next(gen) resumes the body right after the last yield. The body runs until it reaches another yield. The value after that yield becomes the result of next(), and the generator pauses again.
When the body ends, Python raises StopIteration for you. You never write that exception inside a generator. A bare return also ends the generator in the same way.
Because the frame is kept between calls, local state survives:
def counter():
n = 0
while True:
n += 1
yield n
c = counter()
print(next(c), next(c), next(c)) # 1 2 3The variable n is not reset. It lives in the paused generator until the next resume.
A for loop handles all of this
A for loop calls next() for you and stops quietly when it catches StopIteration. That is why you rarely see the exception in everyday code.
def countdown(start):
while start > 0:
yield start
start -= 1
for value in countdown(3):
print(value)Finished means finished
Once a generator is finished, every later next() raises StopIteration again. It does not restart.
def one():
yield "only"
g = one()
print(list(g)) # ['only']
print(list(g)) # []To get the values again, call the generator function to make a new generator object.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Expecting code to run when the generator is called | Nothing prints until the first `next()` | Remember that creation and execution are separate steps |
| Calling `next()` on a finished generator | `StopIteration` | Catch it, or use a `for` loop |
| Reusing a generator after a loop | The second loop gets no values | Create a new generator object |
| Raising `StopIteration` inside the body | `RuntimeError` | Use `return` |
Exercise
What does this code print, and in what order? def pair(): print("a") yield 1 print("b") yield 2 g = pair() print("made") print(next(g))
Show answer
It prints "made", then "a", then "1". Calling pair() runs no code, so "made" comes first. The first next() runs the body up to the first yield, printing "a", and the yielded 1 is printed by the outer print. "b" is never printed because the generator is paused at the first yield and next() is not called again.
Exercise
A generator is created and a for loop consumes it completely. What does a second for loop over the same object do, and why?
Show answer
It does nothing and produces no values. The generator is in the finished state after the first loop, so every next() raises StopIteration right away, and the loop ends at once. You need to call the generator function again to get a fresh generator object.