Sub topic 5
Generator functions: iterators with yield
This chapter assumes you know how to write functions, classes and loops, and that you have met the iterator protocol (__iter__, __next__, StopIteration). Here you will see how a generator function gives you the same result as a hand-written iterator class with much less code.
From iterator class to generator function
A custom iterator class has to track its own state and raise StopIteration when it runs out of values:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]A generator function does the same job. Any function whose body contains yield is a generator function:
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3))) # [3, 2, 1]The attribute self.current became the local variable start. The __next__ method became the loop. There is no explicit StopIteration: when the function body ends, Python raises it for you.
What calling a generator function does
Calling a generator function does not run its body. It returns a generator object, which is an iterator. It has __iter__ and __next__, so for, list() and next() all work on it.
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
stoppedNothing printed when demo() was called. The first next() ran the body up to the first yield. Each later next() resumed right after the previous yield and ran to the next one. The third next() ran off the end of the function, which raised StopIteration.
Why this is useful
The generator keeps its local variables between pauses, so you do not store state by hand. It also produces values only when asked, which means it can describe a sequence that never ends:
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
print(list(islice(fibonacci(), 8))) # [0, 1, 1, 2, 3, 5, 8, 13]fibonacci() has no end, yet the program finishes, because islice stops asking after eight values.
Common mistakes
- Expecting the body to run on the call.
gen = demo()prints nothing. Errors inside the body also appear only at the firstnext(). - Using
return valueas if it wereyield. In a generator,returnends the sequence. It does not produce an item. - Reusing a finished generator. Once it raises
StopIteration, it stays empty. To start over, call the generator function again.
Choosing between a class and a generator
| Situation | Better choice |
|---|---|
| A simple sequence of values with some loop logic | Generator function |
| An object that needs extra methods or attributes beyond iteration | Iterator class |
| A sequence that must be traversed many times | Iterable class whose `__iter__` is a generator |
Exercise
Write a generator function evens(limit) that yields the even numbers from 0 up to but not including limit. What does evens(7) return when you call it, and what does list(evens(7)) give?
Show answer
def evens(limit):
n = 0
while n < limit:
yield n
n += 2
Calling evens(7) returns a generator object and runs none of the body. list(evens(7)) gives [0, 2, 4, 6].
Exercise
In the demo() example, how many times is "middle" printed if you call next(gen) once and then stop?
Show answer
Zero times. One next() runs the body only up to the first yield, so "start" is printed but "middle" is not.