A lazy pipeline connects processing stages that do work as their results are requested, rather than processing the whole input immediately.
Trace pulls through filtering and transformation stages, and see how early stopping affects source reads and retained state.
A log preview needs two matching errors, not every parsed record in the file. Connect the generators you already know so a request for one result pulls only the source work needed to produce it. Then measure the pulls: result length alone cannot tell you whether filtering and limiting really stopped early.

Chain four stages, and nothing runs yet
Every stage has the same shape: take an iterable, loop over it, yield. Because the input can be any iterable, it can be another stage:
Building the chain runs no code in any stage — that's why printing
errors shows only a generator object. Work starts when the for loop at
the bottom asks for the first record. The mistake people make here is
picturing the eager version, where each stage finishes before the next
begins:
def read(lines):
for line in lines:
print("r" + line, end=" ")
yield line
def shout(lines):
for line in lines:
print("s" + line, end=" ")
yield line.upper()
for x in shout(read(["a", "b"])):
print(x, end=" ")If you guessed ra rb sa sb A B, that's how a chain of lists behaves, with
a full list built between every step. A lazy pipeline never builds that
list — these particular stages retain only a small amount of state. The input
container and any collected output still contribute to total memory. The two shapes side by side:
Preparing this topic’s interactive investigation…
Stop a pipeline before it reads the whole log
The biggest win isn't memory — it's that a lazy pipeline can stop. Quarry's preview wants the first two errors from a file that might have ten million lines. Count how many lines actually leave the source:
pulled = 0
def source(n):
global pulled
for i in range(n):
pulled += 1
yield i
evens = (x for x in source(10**9) if x % 2 == 0)
first_two = next(evens), next(evens)
print(first_two, pulled)A take(items, n) stage is how a pipeline says "enough" — it must stop the
moment it has yielded its nth item, never pulling one more than needed:
Four lines pulled out of six. Put if count == n at the top of the loop
instead of after the yield, and take would pull one extra record before
deciding it has enough — with a slow remote source, that's one wasted fetch
every time. The standard library already has this stage: itertools.islice
does exactly what take does, with the same discipline about not
over-pulling, and itertools.chain joins several sources into one stream:
How far a lazy pipeline has to read depends on how common the thing you want is. At 10% errors, finding 20 of them reads about 200 lines; at 1%, about 2,000 — rarer matches mean reading further, but it still stops the moment it has enough. An eager pipeline reads every line regardless, so the same preview on a 10-million-line file costs 10 million reads either way.
Count pulls at the boundary that matters
One requested output can require many input pulls. A filter may reject a million records before yielding one; laziness avoids unnecessary work, not necessary searching. Instrument the source rather than infer work from result length.
The first result is [3] with four source values examined. The second resumes
at 4; it does not rebuild the pipeline. Move the condition to n >= 9 and
predict both the first result and the pull log before running. “No result” can
still mean the whole finite source was consumed.
The placement of a limit changes the question. Filtering the first ten rows asks how many matches occur in that prefix. Taking ten matches after filtering may read far more than ten rows. Preserve this distinction in previews and API pagination; otherwise a “limit” can accidentally change business meaning.
Memory depends on each stage's retained state. These simple transforms retain
only a few records; sorting materialises all its input, deduplication remembers
seen keys, and grouping may grow with distinct groups. tee can buffer the gap
between consumers. A chain of generators is not automatically bounded-memory.
When diagnosing it, list each retained collection and what makes it grow.
Reuse a parsed stream for two different answers
Some operations — sorted(), counting how often each level appears — need
the whole stream before they can produce anything. Put those last,
after the filters have made the stream as small as possible; sorting 200
errors is cheap, sorting ten million lines first isn't.
Every stage is a generator, so every stage is single-use. That catches people the first time they try to get two different answers from one stream:
Run it and look at infos. Then change the code so both lists come out right, without reading lines into anything but the two answers.
There's no error, just a silently empty list — the dangerous kind of bug. If two consumers need the same stream, either give each one its own fresh pipeline built from a function, or split the records in a single pass.
Quick practice
nums = (n for n in range(5))
doubled = (n * 2 for n in nums)
print(next(doubled), next(doubled), list(nums))from itertools import islice
def forever():
n = 0
while True:
yield n
n += 1
print(list(islice(forever(), 3, 6)))🎯 Your turn
Build Quarry's log pipeline from four stages, and prove it's lazy.
counted(lines, tally): yields every line unchanged, adding 1 totally["pulled"]for each one it pulls (provided).parse(lines): skips blank lines and yields{"level": ..., "msg": ...}, splitting each line at its first space.at_level(records, level): yields only records at that level.take(items, n): yields at mostnitems and stops as soon as it has yielded thenth, without pulling another. Whennis 0 it yields nothing and pulls nothing.
Then pipe(lines, level, limit) chains them and returns
{"records": [msg, ...], "pulled": n}:
pipe(["INFO boot", "ERROR disk full", "INFO tick", "ERROR fan stuck", "ERROR late", "INFO bye"], "ERROR", 2)→{"records": ["disk full", "fan stuck"], "pulled": 4}
Hint: take checks n <= 0 before its loop and count == n after
each yield. Build the chain from the inside out: take(at_level(parse(counted(lines, tally)), level), limit).
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write two generator stages: evens(numbers), which yields only the even numbers, and squares(numbers), which yields each number squared. squares_of_evens(numbers) (already written) chains them.
Write first_match(lines, word), which returns {"line": ..., "pulled": n}: the first line containing word (or None if there isn't one), and how many lines were pulled from counted to find it. It should stop reading at the first match.
Quarry's config lists pipeline stages by name. Write run_stages(values, names), which applies the stages in STAGES in the order names gives them, each wrapping the one before, and returns the final list. An empty names returns the values unchanged.
Two of Quarry's sources each deliver timestamps in sorted order, and they may be too big to hold. Write the generator merge_sorted(a, b), which yields every item from both in sorted order while holding only one item from each at a time (no sorted(), no list() of the inputs). merged(a, b) returns the list.
A sensor sends timestamps (seconds, sorted). A session is a run of timestamps where each is no more than gap after the one before. Write the generator sessions(times, gap), which yields [start, end, count] for each session as soon as it knows the session has ended, holding only the current session's summary, not its timestamps. session_list(times, gap) returns the list.
In Quarry's generator pipeline, the first log line is read, parsed, filtered and printed before the second line is even read. In the list-based version, every line is read before any is parsed. Explain why the generator version behaves this way, and name two practical consequences for a 200 MB log, one about memory and one about stopping early. Then name one kind of stage that can't work this way.