Python Generators: Pipelines, yield from, send()
A generator is a function that remembers where it stopped, and almost every advanced technique follows from that one fact. Pipelines chain generators so each stage transforms lazily, yield from delegates to sub-iterators without manual loops, and send pushes values back into a suspended generator, turning it into a coroutine. The same memory profile that makes generators ideal for large files makes them awkward when you need to iterate twice or when cleanup has to happen at exactly the right moment. This lesson builds each technique from the execution model outward, so the behaviour stops being surprising.
What You'll Learn
- 1Compose multi-stage generator pipelines that stay lazy end to end
- 2Delegate with yield from and understand what it forwards
- 3Drive generators with send, throw, and close for two-way flows
- 4Handle cleanup and single-use limitations deliberately
Execution model: suspend, resume, remember
Calling a generator function runs no body code. It returns a generator object, and the body executes only on the first next, running until it hits a yield, at which point it freezes: local variables, instruction pointer, and exception state are all preserved. The yield expression evaluates to whatever arrives via send â which is None for an ordinary next â and the cycle repeats until the function returns, raising StopIteration.
Two consequences explain most generator confusion. First, code before the first yield runs on first advance, not at definition, so a generator that opens a file does not open it until someone iterates. Second, generators are single-use: once exhausted, calling next raises StopIteration forever, and the body will never run again. Anything that must be visited twice needs to be materialised into a list, or regenerated by calling the factory function again.
def trace(label, items):
print(f"creating {label}")
for item in items:
print(f"{label} yields {item}")
yield item
print("before iteration")
stage = trace("A", [1, 2])
print("created, nothing ran yet")
print(next(stage)) # body starts here, runs to first yield
print(next(stage)) # resumes exactly where it froze
try:
next(stage)
except StopIteration:
print("exhausted")
print(list(trace("B", [1]))) # new call, fresh state, one more full pass
The creating line printed before any yields shows the boundary clearly: construction is free, and everything the body does is deferred to iteration. That is why generators are safe to build eagerly and expensive only to consume.
Pipelines: stages that never materialise
The pipeline pattern arranges generators in layers â read, filter, parse, aggregate â so a value flows through every stage before the next one is pulled. Memory stays proportional to one element rather than to the dataset, which is what lets a script process files larger than RAM. The compositional syntax is just nested calls, and because each stage accepts an iterable and returns a generator, stages can be rearranged without touching their bodies.
The discipline that keeps a pipeline honest is that no stage may call list() internally. A stage that materialises collapses the laziness of everything upstream of it: the reader now loads the whole file before the filter sees a single line. When you genuinely need the whole input â a sort, a global count â make that stage the explicit boundary and name it accordingly, so the memory cost is visible in the code rather than hidden in a helper.
import csv
def read_lines(path):
with open(path, encoding="utf-8") as handle:
for line in handle:
yield line.rstrip("\r\n")
def drop_comments(lines):
for line in lines:
if line and not line.startswith("#"):
yield line
def parse_rows(lines):
reader = csv.reader(lines)
for row in reader:
yield row
def keep_positive(rows, column):
for row in rows:
try:
if int(row[column]) > 0:
yield row
except (IndexError, ValueError):
continue
def running_total(rows, column):
total = 0
for row in rows:
total += int(row[column])
yield total
pipeline = running_total(
keep_positive(
parse_rows(
drop_comments(
read_lines("data.csv")
)
),
column=1,
),
column=1,
)
print(next(pipeline)) # first pull reads exactly one line from disk
Every next on the final generator causes one line to be read, one comment check, one parse, one filter, and one accumulation â a single row's worth of work at a time. When the numbers disagree with expectations, print the stage boundaries and confirm which layer is quietly buffering.
yield from: delegation without boilerplate
yield from inner hands iteration to inner and relays every value straight to the consumer, including values sent back with send and exceptions thrown with throw. It replaces the manual loop of for value in inner: yield value, and the difference is not just brevity: delegation keeps the two-way channel open, so a sub-generator can receive data from the outermost caller. It also returns the sub-generator's return value, accessible through the StopIteration.value that ends the loop.
Two practical uses dominate. Flattening nested structures becomes a recursive yield from, which reads as the recursive definition itself. And splitting a large generator into cooperating sub-generators keeps each part independently testable while the outer generator remains the single entry point for the caller.
def flatten(items):
for item in items:
if isinstance(item, (list, tuple)):
yield from flatten(item)
else:
yield item
def read_config(path):
yield from read_lines(path) # manual loop would hide delegation
def stage_one():
yield 1
yield 2
return "done-one"
def stage_two():
yield 3
result = yield from stage_one()
print("delegated returned:", result)
yield 4
print(list(flatten([1, [2, [3, 4]], (5, 6)]))) # [1, 2, 3, 4, 5, 6]
print(list(stage_two())) # [3, 1, 2, 4]
# delegated returned: done-one
One limitation worth remembering: yield from passes through values but does not make an inner iterator re-iterable. If the consumer abandons the pipeline early, the delegated generator is simply left suspended, which is exactly where the cleanup section below has to run.
send, throw, and close: data flows both ways
gen.send(value) resumes the generator with value delivered as the result of the yield expression; gen.throw(Exc) raises inside the generator at the suspended point; gen.close() raises GeneratorExit so the body can run cleanup. Together they make a generator a coroutine: a function that processes a stream of inputs and can be told to stop or interrupted mid-flight.
The one mechanical rule is that a generator must be advanced to its first yield before send can deliver anything â gen.send(x) before the first advance raises AttributeError, because there is no suspended yield yet. The idiom is a priming next(gen), or writing the body so the first statement is yield in a wrapper. From then on, send and next are interchangeable whenever you are not delivering data.
def accumulator(log):
total = 0
received = 0
while True:
try:
value = yield total
except ValueError:
log.append("rejected value")
continue
if value is None:
break
total += value
received += 1
audit = []
acc = accumulator(audit)
next(acc) # prime to the first yield
print(acc.send(10)) # 10
print(acc.send(20)) # 30
try:
acc.throw(ValueError)
except ValueError:
pass
print(audit) # ['rejected value']
acc.close()
print("closed cleanly")
def bounded_stream(limit):
try:
for i in range(limit):
yield i
finally:
print("cleanup ran")
stream = bounded_stream(3)
print(next(stream), next(stream))
stream.close() # triggers the finally even on early exit
The finally in bounded_stream runs on close, on garbage collection of an abandoned generator, and on normal exhaustion â which makes generators a fine home for cleanup code, provided the consumer either exhausts or explicitly closes them. Relying on garbage collection alone leaves timing to the interpreter's discretion.
Knowing when a generator is the wrong shape
Generators shine for one-pass transformations of large or infinite inputs. They are the wrong shape when the consumer needs random access, multiple passes, or a length up front â each of those requires materialising, at which point a list or a dictionary is the honest choice. Confusing the two produces code that appears to work on a list and then silently yields nothing the second time it is looped over.
The table below summarises the trade-offs that come up most often in review.
| Question | Generator | List | Plain iterator |
|---|---|---|---|
| Memory while processing | One element at a time | Entire collection | Depends on source |
| Can you iterate twice? | No â regenerate or materialise | Yes | Rarely |
| Knows its length? | No | Yes | No |
| Early exit cost | Immediate | Already paid | Immediate |
| Suits infinite input? | Yes | Impossible | Sometimes |
| Random access | No | Yes | No |
A related trap is eager work inside the generator body: logging, opening connections, or computing defaults at definition time defeats the purpose. Keep the body cheap until the first next, and push any unavoidable setup into a context manager so it runs when iteration actually begins.
import itertools
import sys
def naturals(start=0):
n = start
while True:
yield n
n += 1
def first_even_above(limit, minimum):
return next(
x for x in naturals(minimum)
if x % 2 == 0 and x > limit
)
print(first_even_above(10, 0)) # 12 â stopped by consumer
print(list(itertools.islice(naturals(), 5))) # [0, 1, 2, 3, 4]
sizes = [sys.getsizeof(list(itertools.islice(naturals(), n))) for n in (100, 1000)]
print(sizes[0], sizes[1], "list cost grows linearly with n")
islice is the idiomatic way to bound an infinite stream, and next with a default is the idiomatic way to stop at the first match: both terminate without pulling the whole sequence, which is the entire reason to keep the source lazy.
Cleanup, errors, and composition discipline
A generator that owns a resource must release it on every exit path â normal exhaustion, early abandonment, and exceptions travelling through from the consumer. Wrapping the body in try and finally covers all three, and contextlib.closing or a with block inside the generator does it more clearly than manual bookkeeping. Without that, an abandoned pipeline holds file descriptors until garbage collection notices.
Error handling inside a pipeline deserves a decision rather than a default. Swallowing exceptions and skipping bad rows is correct for log ingestion where partial results beat failure, and wrong for financial data where silent gaps are worse than a crash. Whichever you choose, make it visible: count skipped rows, emit a warning, and surface the count at the end so an error rate that quietly doubles does not go unnoticed for a week.
Common Mistakes
Iterating the same generator twice and getting nothing the second time
Fix: Regenerate by calling the factory function, or materialise deliberately with list when you truly need multiple passes
Calling send before the generator has reached its first yield
Fix: Prime with next(gen) once before sending, or structure the body with an initial yield
Materialising inside one stage with list, silently breaking laziness upstream
Fix: Keep every stage yielding, and mark the stage that must buffer with a clear name and comment
Leaving resource cleanup to garbage collection
Fix: Use try and finally or a with block inside the generator so close and exhaustion both release
Swallowing row-level errors without counting them
Fix: Track and report skipped records so a rising failure rate is visible in logs and metrics
Best Practices
- Write each stage to accept an iterable and yield results, so stages compose freely
- Use yield from for delegation instead of manual relay loops
- Prime a coroutine with next before the first send
- Bound infinite streams with islice and first-match queries with next
- Keep setup inside the generator body so cost follows consumption, not definition
Interview Questions
Q1: What is the difference between yield and return in a generator?
return ends the generator and raises StopIteration, optionally carrying a value accessible as StopIteration.value; yield suspends and can be resumed. A generator may yield many times but returns once.
Q2: Why does calling send immediately after creation fail?
The body has not run to the first yield yet, so there is no suspended yield expression to receive the value. Prime the generator with next(gen) first, then send.
Q3: How do you release resources held by a generator the caller abandons?
Put the cleanup in try and finally inside the generator, or use a with block in the body. When the caller closes the generator or drops the last reference, GeneratorExit is raised at the yield and the finally runs.
Key Takeaways
- Generators defer execution until first advance and remember their exact position
- Pipelines stay lazy only if no stage materialises the whole input
- yield from delegates values, sent data, and exceptions while forwarding the return value
- send, throw, and close make a generator a two-way coroutine with cleanup hooks
- Single-use semantics mean multiple passes require regeneration or an explicit list