Sub topic 9
Chaining generators into pipelines
This chapter assumes you can write a generator function with yield, that you know a generator expression is a lazy version of a list comprehension, and that you have seen how for loops call iter() and next(). If any of that is unclear, review the earlier chapters on generator functions and generator expressions first.
What a pipeline is
A generator pipeline is a chain of generators in which each stage consumes the output of the previous stage. The first stage reads from a source such as a list, a file, or a network stream. Each later stage takes an iterable as input and yields transformed or filtered items.
Each stage does one small job. You combine stages by passing one stage's result to the next. Nothing runs until something at the end of the chain asks for a value.
This is the same idea as a Unix shell pipe such as cat log | grep error | sort. The difference is that the stages here are ordinary Python functions.
Here is the example from the plan:
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']non_empty drops blank lines. shout converts each line to uppercase. Calling shout(non_empty(...)) builds the chain but runs no stage body. The list() call at the end drives the whole pipeline.
How items flow through the chain
A pipeline is pull-based. The consumer at the end asks for one item, and that request travels backwards through the chain until it reaches the source.
Take the input ["a", "", "b"] and follow list() as it pulls from shout:
list()callsnext()on theshoutgenerator.shoutstarts itsforloop, which callsnext()on thenon_emptygenerator.non_emptypulls"a"from the list. The line is not blank, so it yields"a".shoutreceives"a"and yields"A"tolist().- On the next request,
non_emptyresumes. It pulls"", finds it blank, skips it, pulls"b", and yields it. shoutyields"B".- The final request makes
non_emptyreach the end of the list. It finishes and raisesStopIteration. Theforloop inshoutcatches that and ends too, solist()seesStopIterationand stops.
Only one item is in flight at a time. Item "a" has been completely processed before "b" is read from the source. This is the property that makes pipelines cheap in memory.
A realistic example: processing log lines
Pipelines pay off when the data is large. The next example processes a log, counts error lines per service, and never holds the whole log in memory. It uses an in-memory list of strings so that you can run it as written. In real use you would replace the source with an open file, because a file object is also an iterator over lines.
def read_lines(source):
for line in source:
yield line.rstrip("\n")
def parse(lines):
for line in lines:
parts = line.split(" ", 2)
if len(parts) == 3:
level, service, message = parts
yield {"level": level, "service": service, "message": message}
def only_level(records, level):
for record in records:
if record["level"] == level:
yield record
log = [
"INFO api started\n",
"ERROR api timeout talking to db\n",
"bad line\n",
"ERROR worker crashed\n",
"ERROR api disk full\n",
]
errors = only_level(parse(read_lines(log)), "ERROR")
counts = {}
for record in errors:
counts[record["service"]] = counts.get(record["service"], 0) + 1
print(counts) # {'api': 2, 'worker': 1}Notice three design choices:
- Each stage has one job and can be tested alone by passing it a small list.
only_leveltakes extra arguments. A stage is any function that accepts an iterable and returns an iterator, so it can take whatever else it needs.- The malformed line
"bad line"is dropped insideparse. A stage may yield fewer items than it receives.
The final for loop is the consumer. If you stopped it early with break, the earlier stages would stop producing as well, and the rest of the log would never be read.
Mixing generator functions and expressions
A stage does not have to be a full function. A generator expression works well when the stage is a single transformation or filter:
def numbers():
for n in range(1, 11):
yield n
evens = (n for n in numbers() if n % 2 == 0)
squares = (n * n for n in evens)
print(sum(squares)) # 220sum() is a consumer. It pulls from squares, which pulls from evens, which pulls from numbers. No intermediate list is created.
Use a generator expression for a one-line stage. Use a generator function when a stage needs a local variable, several statements, or an if/else that yields different things.
When a generator expression is the only argument to a function, you can omit the extra parentheses: sum(n * n for n in evens).
Stages that keep state
A stage can hold state between items, because a generator keeps its local variables while paused. This lets you write stages that look at more than one item at a time.
def running_average(values):
total = 0
count = 0
for value in values:
total += value
count += 1
yield total / count
print(list(running_average([10, 20, 30]))) # [10.0, 15.0, 20.0]The stage still emits one output per input and uses constant memory. It stores only two numbers, however long the input is.
Some stages must hold more. A deduplicating stage keeps a set of values it has seen, and a "batching" stage keeps a small buffer:
def batches(items, size):
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
print(list(batches(range(7), 3))) # [[0, 1, 2], [3, 4, 5], [6]]The final if batch: handles the leftover items when the input does not divide evenly. Forgetting it is a common bug: the last partial batch is silently lost.
Infinite sources and early stopping
A pipeline can start from an infinite source as long as something downstream limits it. Because items are pulled one at a time, a stage that stops asking for items stops the whole chain.
from itertools import count, islice
def naturals():
return count(1)
def odd(numbers):
for n in numbers:
if n % 2:
yield n
def squared(numbers):
for n in numbers:
yield n * n
first_five = islice(squared(odd(naturals())), 5)
print(list(first_five)) # [1, 9, 25, 49, 81]islice is the consumer that decides when to stop. After five values it stops pulling, and the generators are left suspended. The later chapter on itertools covers islice and related tools in more detail.
Reading a pipeline: debugging and ordering
Because stages are lazy, errors appear at the point of consumption, not at the point where you wrote the faulty stage. A bug in parse will raise its exception inside the loop that consumes errors, and the traceback will show every stage that was active at that moment. Read it from the bottom up: the last frame is the stage that failed, and the frames above it are the stages that were waiting on it.
To see what a stage emits, insert a temporary tap stage:
def tap(label, items):
for item in items:
print(label, item)
yield item
data = tap("after filter", (n for n in range(6) if n % 2 == 0))
print(sum(data))This prints after filter 0, after filter 2, after filter 4, and then 6. The tap changes nothing about the values.
Stage order also affects cost. Put cheap filters that remove many items early, so that expensive stages see fewer items. For example, filter by log level before you run an expensive parse of the message body.
Pitfalls specific to pipelines
- Single use. A pipeline is a chain of single-use iterators. After you consume it once, it is exhausted. To run it again, rebuild the chain by calling the stage functions again. Wrapping the construction in a function is the simplest way to do this.
- Breaking laziness with
list()orsorted(). Callinglist()on a stage in the middle holds every item in memory.sorted()andmax()with a full scan also need the whole input. Do this only when a stage really needs all the data, such as sorting. - Sharing one source between two pipelines. If two chains read from the same iterator, they take items from each other. Each chain then sees only some of the items.
- Side effects at construction. Nothing in a generator body runs when you call the function. If you expect a file to open or a message to print at that moment, it will not happen until the first
next().
Here is the sharing problem in code:
source = iter([1, 2, 3, 4])
evens = (n for n in source if n % 2 == 0)
odds = (n for n in source if n % 2 == 1)
print(list(evens)) # [2, 4]
print(list(odds)) # []The evens chain consumed the whole of source, so odds found nothing. If you need two independent passes, create two separate iterators from the underlying data, or use itertools.tee and accept the memory cost of buffering.
Summary table
| Concern | Guidance |
|---|---|
| One-line transform or filter | Generator expression |
| Multi-statement stage or state | Generator function |
| Reuse the pipeline | Rebuild the chain; it cannot be rewound |
| Limit an infinite stream | `islice` or a `break` in the consumer |
| Inspect values mid-chain | Temporary tap stage |
| Memory use | Constant per stage, unless a stage buffers |
Exercise
Write a pipeline that takes the list ["3", "x", "5", "", "8"], skips entries that are not digit strings, converts the rest to integers, and sums them. Use at least one generator function and do not build an intermediate list. What value does it print?
Show answer
One solution: def digitsonly(items): for item in items: if item.isdigit(): yield item def toint(items): for item in items: yield int(item) print(sum(toint(digitsonly(["3", "x", "5", "", "8"])))) It prints 16. The strings "x" and "" fail isdigit() and are dropped, leaving 3, 5 and 8. The empty string returns False from isdigit(), so it is skipped.
Exercise
A learner builds lines = read_lines(log) and errors = only_level(parse(lines), "ERROR"). They call list(errors) twice and the second call returns an empty list. Why, and how do they fix it?
Show answer
The pipeline is a chain of generators, which are single-use. The first list() call exhausts every stage, so the second call finds them finished and gets nothing. To fix it, rebuild the chain before the second pass, for example by wrapping the construction in a function such as def makeerrors(): return onlylevel(parse(read_lines(log)), "ERROR") and calling it each time.