Sub topic 13
Building lazy pipelines from several tools
A lazy pipeline connects several iterator-producing steps so that each item travels through every step before the next item is read. Nothing is computed until a consumer such as a for loop, list(), sum() or next() asks for a value. This chapter shows how to combine the tools from earlier chapters into pipelines and how to keep them correct.
Prerequisites
This chapter assumes you know:
- The difference between an iterable and an iterator, and that iterators are exhausted after one pass.
- Generator expressions and basic
yieldfunctions. - The individual tools used here:
count,islice,chain.from_iterable,filterfalse,takewhile,groupby,pairwiseandbatched.
batched needs Python 3.12 or later. pairwise needs 3.10 or later.
The shape of a pipeline
A pipeline has three parts: a source, zero or more transformations, and a consumer. The source can be a list, a file, or an infinite iterator. Each transformation takes an iterator and returns another iterator. The consumer is the only part that pulls data.
The dotted arrow matters. The consumer pulls, and each stage asks the stage before it for exactly one item at a time. Memory use stays constant however large the source is.
A first pipeline
This pipeline starts from an infinite source and keeps only what it needs:
from itertools import count, islice
squares = (n * n for n in count(1))
odd_squares = (s for s in squares if s % 2 == 1)
print(list(islice(odd_squares, 5)))It prints [1, 9, 25, 49, 81]. The count(1) source never ends, but islice asks for only five results, so the work stops there. Putting a bound at the end of the pipeline is the standard way to tame an infinite source.
Seeing the laziness
You can prove that stages run on demand by adding a stage that prints:
def noisy(items):
for x in items:
print("produce", x)
yield x
pipeline = (x * 10 for x in noisy([1, 2, 3, 4]) if x % 2 == 0)
first = next(pipeline)
print("got", first)The output is:
produce 1
produce 2
got 20Items 3 and 4 are never produced. Creating pipeline ran nothing. The call to next pulled items until one passed the filter, then stopped.
Order of stages
The order of stages changes how much work is done, even though the result may be identical. Two rules cover most cases:
- Put filters before expensive transformations, so you transform fewer items.
- Put bounding tools such as
isliceandtakewhileas early as the logic allows, so upstream stages do less work.
The exception is when a bound depends on a transformed value. If you want the first five squares above 1000, you must square first and filter second, because the condition applies to the squares.
A log-processing pipeline
This example reads lines from several sources, drops comments and blank lines, parses the rest, and summarises each day. The sources are lists so the code runs as shown, but file objects work the same way.
from itertools import chain, filterfalse, groupby
from operator import itemgetter
def read_all(sources):
return chain.from_iterable(sources)
def drop_noise(lines):
stripped = (line.strip() for line in lines)
return filterfalse(lambda s: not s or s.startswith("#"), stripped)
def parse(lines):
return (line.split(maxsplit=2) for line in lines)
def summarize(rows):
for day, group in groupby(rows, key=itemgetter(0)):
levels = [row[1] for row in group]
yield day, len(levels), levels.count("ERROR")
file_a = ["# header", "2026-11-01 INFO start", "2026-11-01 WARN disk 91", ""]
file_b = ["2026-11-02 INFO start", "2026-11-02 ERROR disk full", "# trailer"]
summary = summarize(parse(drop_noise(read_all([file_a, file_b]))))
for day, total, errors in summary:
print(day, total, errors)It prints:
2026-11-01 2 0
2026-11-02 2 1Each stage is a small function that takes an iterable and returns an iterator. This has three benefits:
- You can test each stage alone with a short list.
- You can reorder, add or remove stages without touching the others.
- Reading the call chain from the inside out tells you the data flow.
Only one line from each source is in flight at a time, except inside groupby, where the list comprehension holds one day's levels. That group is the largest thing held in memory.
Why groupby works here
groupby groups only consecutive items with equal keys. The log files are already in date order, so no sort is needed. If the input were not ordered, you would have to sort it first. That forces the whole stream into memory and breaks the constant-memory property. For unordered data, a dictionary of counters is often a better fit than groupby.
Stopping early
A pipeline can stop as soon as it has its answer. To find the first day with an error:
first_bad_day = next((day for day, total, errors in summarize(rows) if errors), None)Here rows stands for the parsed iterator from the earlier example. The second argument to next is a default returned if no day matches, which avoids a StopIteration exception. Because the pipeline is lazy, the remaining input is never read.
Combining windows, batches and running results
Several tools fit together when a problem has more than one step. This code counts how many readings rose compared with the previous reading, then shows a running total:
from itertools import accumulate, pairwise
readings = [3, 5, 4, 8, 9, 7]
rises = sum(1 for a, b in pairwise(readings) if b > a)
print(rises)
print(list(accumulate(readings)))The first line prints 3, from the pairs (3, 5), (4, 8) and (8, 9). The second prints [3, 8, 12, 20, 29, 36].
To process an unbounded stream in groups, combine batched with islice:
from itertools import batched, count, islice
stream = (n * n for n in count(1))
for batch in islice(batched(stream, 4), 3):
print(batch)This prints three tuples: (1, 4, 9, 16), (25, 36, 49, 64) and (81, 100, 121, 144). islice bounds the number of batches, and batched bounds the size of each.
Reusing a pipeline
A pipeline is a chain of iterators, so it can be consumed only once. A second pass sees nothing:
from itertools import filterfalse
def make_pipeline(limit):
return filterfalse(lambda n: n % 3 == 0, range(limit))
pipeline = make_pipeline(10)
print(list(pipeline))
print(list(pipeline))
print(list(make_pipeline(10)))The output is [1, 2, 4, 5, 7, 8], then [], then [1, 2, 4, 5, 7, 8] again. Wrap the construction in a function and call it each time you need a fresh pass. Do not use tee to fix this for large inputs, because it buffers every item that one copy has read and the other has not.
Debugging a pipeline
Because stages run only on demand, a bug in an early stage may show up far from its cause. A traceback appears at the point of consumption. These techniques help:
- Test each stage on a small list, as in the log example.
- Insert a temporary tap stage like
noisyabove to print what passes through. - Look at the first few items with
list(islice(stage, 5)). Remember this consumes them, so rebuild the pipeline afterwards.
Edge cases
- Closed resources. If a pipeline reads from a file opened in a
withblock, the file is closed when the block ends. A pipeline returned from the block and consumed afterwards raisesValueError: I/O operation on closed file. Consume the pipeline inside the block, or open the file inside a generator function that does the iteration. - Late errors. An exception in a stage appears only when that item is pulled. Code after the pipeline definition may run happily before the error shows up.
- Late binding in generator expressions. The outermost iterable of a generator expression is evaluated immediately. Everything else is evaluated lazily. If a lambda or condition refers to a variable you change later, it uses the new value when the item is pulled.
- Shared sources. Two pipelines built from the same iterator compete for its items. Each item goes to whichever pipeline asks first.
- Debug-friendly fallback. If a pipeline becomes hard to follow, it is fine to store an intermediate result in a list. Choose clarity over laziness when the data fits in memory.
When a pipeline is the wrong tool
A lazy pipeline suits a single pass over a large or unbounded stream. A plain list and a loop is better when you need random access, several passes, len(), or simple code over a small dataset. A pipeline of eight stages can be harder to read than a four-line loop with a clear variable name.
Summary of the design rules
| Goal | Technique |
|---|---|
| Handle an unbounded source | Put `islice` or `takewhile` at the end or early |
| Reduce work | Filter before transforming |
| Keep stages testable | Write each stage as a function from iterable to iterator |
| Run the pipeline again | Rebuild it from a factory function |
| Group by key | Ensure the input is ordered by that key first |
Exercise
What does this code print, and what value does the final next(nums) return?
from itertools import count, islice, takewhile
nums = (n * n for n in count(1))
small = takewhile(lambda x: x < 50, nums)
print(list(islice(small, 3)))
print(next(nums))
Show answer
It prints [1, 4, 9], then 16. The islice stage requests exactly three items from takewhile and stops without asking for a fourth, so nums has produced only 1, 4 and 9. The next value from nums is 16.
Exercise
A learner writes evens = filter(lambda n: n % 2 == 0, range(10)), then runs print(sum(evens)) followed by print(sum(evens)). What does each line print, and how should the code change to get the same answer twice?
Show answer
The first line prints 20 and the second prints 0, because filter returns an iterator that the first sum exhausted. To get 20 twice, build the iterator again for each use, for example with a function def make_evens(): return filter(lambda n: n % 2 == 0, range(10)) and call sum(make_evens()) each time. Storing the result with list(...) also works when the data is small.