Sub topic 9
Chaining generators into pipelines
This chapter assumes you can write a generator function with yield and know that a generator is a single-use iterator. A pipeline connects several generators so that each one reads from the one before it. Data moves through the stages one item at a time.
The idea
Each stage is a generator that takes an iterable as its argument and yields transformed or filtered items. Because a generator is itself an iterable, the output of one stage can be the input of the next.
def non_empty(lines):
for line in lines:
if line.strip():
yield line
def shout(lines):
for line in lines:
yield line.upper()
print(list(shout(non_empty(["a", "", "b"])))) # ['A', 'B']Calling non_empty([...]) runs none of its body. It only creates a generator object. The same is true of shout(...). Work starts when list() asks the outermost generator for a value.
How items flow
When the consumer asks shout for an item, shout asks non_empty, and non_empty asks the source list. The first item travels all the way through the pipeline before the second item is read. No stage builds an intermediate list.
This is called pull-based flow. The consumer sets the pace, and a stage never does work nobody requested.
A realistic example
Here is a small log filter. Each stage does one job.
import io
def read_lines(f):
for line in f:
yield line.rstrip("\n")
def only_errors(lines):
for line in lines:
if line.startswith("ERROR"):
yield line
def messages(lines):
for line in lines:
yield line.split(" ", 1)[1]
log = io.StringIO("INFO start\nERROR disk full\nINFO retry\nERROR timeout\n")
for msg in messages(only_errors(read_lines(log))):
print(msg)
# disk full
# timeoutThe same code works on a file opened with open(), because a file object is also iterable. A log of many gigabytes would use about the same memory as this four-line one, since only one line is alive at a time.
You can also mix in generator expressions for simple stages:
import io
log = io.StringIO("INFO start\nERROR disk full\nINFO retry\n")
lines = (line.rstrip("\n") for line in log)
errors = (line for line in lines if line.startswith("ERROR"))
print(list(errors)) # ['ERROR disk full']Use a generator function when a stage needs several statements, state, or try/finally. Use an expression for a one-line map or filter.
Why pipelines are worth it
- Each stage is small. You can test a stage alone by passing it a plain list.
- Stages are reusable.
shoutworks on any iterable of strings. - Early exit is cheap. If the consumer stops after the first result, for example with
next(), the stages upstream read only as many items as were needed.
Common mistakes
- Calling
list()in the middle. Wrapping a stage inlist()forces the whole input into memory and breaks the lazy flow. - Expecting errors at creation time. An exception inside a stage appears only when that stage first runs, which can be far from the line that built the pipeline.
- Reading the same stage twice. Two consumers sharing one stage split its items between them.
Exercise
Write a stage first_words(lines) that yields the first word of each line, then chain it after non_empty. What does list(first_words(non_empty(["go now", "", "stop"]))) return, and which stage sees the empty string last?
Show answer
Define def first_words(lines): with for line in lines: yield line.split()[0]. The call returns ['go', 'stop']. The source list passes the empty string only to non_empty, which discards it, so first_words never sees it. Without that filter, "".split()[0] would raise IndexError.