Python Fundamentals · Objects, Errors and Generators
Generators and yield
A generator hands out values one at a time and pauses in between. Watch it freeze at each yield and pick up exactly where it left off.
generators.py
def countdown(n):
while n > 0:
yield n # hand back one value, then pause right here
n = n - 1
ticks = countdown(3) # nothing runs yet: this only makes the generator
first = next(ticks) # runs until the first yield
rest = []
for t in ticks: # carries on from where it paused
rest.append(t)
print(first, rest)
Step by step
- Python defines the function
countdown(). Its body does not run yet: it runs each time the function is called. - Calling countdown(3) does not run its body. It just creates a paused generator object.
- next() runs the generator until the first yield…
- Python checks
n > 0 to decide whether the loop keeps going. - …which hands back 3 and freezes the generator right here, keeping n = 3.
- next() runs the generator until the first yield…
- The value it returned, [], is stored in
rest. - The for loop asks the generator for its next value, which wakes it up where it paused.
- The for loop asks for the next value: the generator resumes after the yield, with n still 3.
- Python checks
n > 0 to decide whether the loop keeps going. - Line runs:
yield n # hand back one value, then pause right here. - The for loop asks the generator for its next value, which wakes it up where it paused.
- 2 is added to the end of the list that
rest points to. - The for loop asks the generator for its next value, which wakes it up where it paused.
n changes from 2 to 1.- n = 1: still > 0.
- Line runs:
yield n # hand back one value, then pause right here. - The for loop asks the generator for its next value, which wakes it up where it paused.
- 1 is added to the end of the list that
rest points to. - The for loop asks the generator for its next value, which wakes it up where it paused.
n changes from 1 to 0.- n = 0: the while ends, the generator finishes, and the for loop stops.
- The for loop asks the generator for its next value, which wakes it up where it paused.
- first = 3 and rest = [2, 1]. The generator produced each value only when asked, pausing in between.