Sub topic 5
Generator functions: iterators with yield
What this chapter assumes
You should know how to write functions and classes, and how try/except works. You should also know the iterator protocol from the earlier chapters: iter() returns an iterator, next() pulls a value, and StopIteration marks the end. If you have written a class with __iter__ and __next__, you are ready.
From a class to a function
Writing an iterator class means managing state by hand. Here is the Countdown class from the previous chapter:
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 with less code:
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3))) # [3, 2, 1]The class stores its position in self.current and raises StopIteration itself. The generator keeps its position in the local variable start, in the place where execution paused. When the function body ends, Python raises StopIteration for you.
A generator function is any function whose body contains the yield keyword. Python compiles it differently from an ordinary function. You can check this with the inspect module:
import inspect
def countdown(start):
while start > 0:
yield start
start -= 1
print(inspect.isgeneratorfunction(countdown)) # True
print(inspect.isgenerator(countdown(3))) # TrueWhat calling a generator function does
Calling a normal function runs its body. Calling a generator function runs none of it. Python creates a generator object and returns it immediately. This object is an iterator, so it has __next__ and its __iter__ returns itself:
def countdown(start):
while start > 0:
yield start
start -= 1
g = countdown(3)
print(type(g).__name__) # generator
print(iter(g) is g) # True
print(hasattr(g, "__next__")) # True
print(next(g)) # 3The body starts running only on the first next(g). It runs until it reaches a yield, hands the value to the caller, and pauses with all its local variables intact. The next next(g) resumes right after that yield.
The next chapter covers this execution model in more detail. For now, remember the rule that nothing runs until the first next().
yield compared with return
Both keywords hand control back to the caller, but they differ in what happens to the function afterwards.
| Aspect | Normal function with `return` | Generator function with `yield` |
|---|---|---|
| Calling it | Runs the body | Returns a generator object |
| Values produced | One | Any number, one per `next()` |
| Local variables after handing back a value | Discarded | Kept until the generator finishes |
| End of the body | Returns `None` to the caller | Raises `StopIteration` |
A bare return inside a generator ends it early. The consumer sees a normal end of iteration, not an error:
def first_negative_stop(values):
for v in values:
if v < 0:
return
yield v
print(list(first_negative_stop([3, 1, -1, 5]))) # [3, 1]A generator may also contain return value. The value does not appear in the loop. It travels inside the StopIteration exception, and a later chapter shows how to read it.
Keeping state in local variables
Generators are most useful when the state would be awkward to store in attributes. This function splits a sequence into fixed-size pieces:
def chunks(items, size):
for start in range(0, len(items), size):
yield items[start:start + size]
print(list(chunks([1, 2, 3, 4, 5], 2))) # [[1, 2], [3, 4], [5]]The loop variable start and the for loop itself act as the iterator state. You write the loop the way you would for a list, and yield turns each iteration into a value for the caller.
You can also put several yield statements in sequence, or place them in branches. Execution always continues from the last yield that ran:
def header_then_rows(rows):
yield "name,score"
for name, score in rows:
yield f"{name},{score}"
for line in header_then_rows([("ada", 9), ("bob", 7)]):
print(line)This prints name,score, then ada,9, then bob,7.
Generator methods
A method can be a generator. The most common case is __iter__, which gives a class a fresh iterator on every loop:
class Words:
def __init__(self, text):
self.text = text
def __iter__(self):
yield from self.text.split()
w = Words("to be or not")
print(list(w)) # ['to', 'be', 'or', 'not']
print(list(w)) # ['to', 'be', 'or', 'not']Here Words is an iterable, not an iterator. Each call to iter(w) runs __iter__, which returns a new generator. That is why the second list(w) works. The yield from statement forwards every item of the list; it gets its own chapter later.
Edge cases and common errors
A generator with no reachable yield
Python decides that a function is a generator by looking for yield anywhere in the body, even in code that never runs:
def empty():
return
yield
print(list(empty())) # []This is a known idiom for an empty generator. It is also a source of confusion. If you delete the only yield from a generator while refactoring, the function silently becomes an ordinary function that returns None, and the loops that consume it fail with a TypeError.
Errors are raised late
Because the body does not run at call time, argument checks inside a generator do not fire when you call it:
def countdown(start):
if start < 0:
raise ValueError("start must be >= 0")
while start > 0:
yield start
start -= 1
g = countdown(-1) # no error here
try:
next(g) # the error appears only now
except ValueError as e:
print(e) # start must be >= 0When you want an early failure, split the function in two. The outer function validates and returns an inner generator:
def countdown(start):
if start < 0:
raise ValueError("start must be >= 0")
def generate():
current = start
while current > 0:
yield current
current -= 1
return generate()
try:
countdown(-1)
except ValueError as e:
print(e) # start must be >= 0Printing a generator shows nothing useful
print(countdown(3)) shows something like <generator object countdown at 0x...>. Wrap it in list() to inspect the values, but remember that this consumes the generator.
A generator is used up after one pass
A generator object is its own iterator, so it cannot be rewound. After one full loop, a second loop yields nothing. Call the generator function again to get a new object. The pitfalls chapter returns to this.
Summary of the key points
- A function containing
yieldis a generator function. Calling it returns a generator object and runs no body code. - The generator object is an iterator, so it works with
next(),forloops,list(), and any other consumer. - Local variables hold the state between values.
- Reaching the end of the body, or a bare
return, producesStopIteration. - Validation inside the body runs at the first
next(), not at call time.
Exercise
Write a generator function evens(limit) that yields the even numbers from 0 up to but not including limit. What does list(evens(7)) return, and does any of the body run when you only write g = evens(7)?
Show answer
One solution is def evens(limit): n = 0; while n < limit: yield n; n += 2, written on separate lines. list(evens(7)) returns [0, 2, 4, 6]. Writing g = evens(7) runs none of the body, because calling a generator function only creates the generator object. The body starts on the first next(g).
Exercise
The function below is meant to be a generator that yields each line of text with its line number, but a refactor removed its only yield. What does numbered("a\nb") return now, and how do you fix it?
def numbered(text):
for i, line in enumerate(text.splitlines(), start=1):
result = (i, line)
Show answer
Without yield the function is an ordinary function. It runs the loop immediately and returns None, so list(numbered("a\nb")) raises a TypeError. Replace result = (i, line) with yield (i, line). The function then becomes a generator, and list(numbered("a\nb")) gives [(1, 'a'), (2, 'b')].