Explain it simply
Explain it simply
In the earlier generator lesson, a generator was a one-way pipe: values only came out. Now you will turn it into something more like a phone call that goes both ways. The caller can say "add this number" (send), "start over" (throw) or "I am hanging up" (close).
The other idea is connecting pipes. On a factory conveyor belt, one station cleans an item, the next inspects it and the next packs it. Each item passes through every station in turn, and no station piles items up. A generator pipeline works the same way.
Problem → Why → Solution
The problem: keeping running state in globals
Say you want to update an average each time a sensor reading arrives. The quick approach keeps total and count as globals and changes them with the global keyword. Once you need two averages for two sensors, the variables collide, and it is unclear where a reset should happen. State left behind by one test makes the next test fail.
total = 0
count = 0
def add_reading(value):
global total, count # shared by every caller
total += value
count += 1
return total / count
add_reading(10)
add_reading(20)
# A second sensor? A reset? Both mean more globals and more bugs.Why is a generator a better fit?
A generator's local variables survive between yields, and each generator object has its own state. If you can push values in with send(), you need no globals: just create one running_average() object per sensor. A reset can be done with throw() and cleanup with close().
Core concept: two-way generators and delegation
yield is not only a statement but an expression. Writing value = yield average hands average out and pauses; when the generator resumes, the yield expression evaluates to whatever the caller sent. Resuming with next(gen) makes it None, and resuming with gen.send(10) makes it 10. send() runs to the next yield and returns the value that yield produces. A brand-new generator is not paused at a yield yet, so calling send(10) straight away raises TypeError: "can't send non-None value to a just-started generator". That is why you prime it first with next(gen).
gen.throw(exc) raises the exception at the paused yield. If the generator catches it and carries on, throw() returns the value of the next yield; if not, the exception propagates back to the caller. gen.close() raises GeneratorExit at the pause point and runs finally and with blocks, which makes it the place for cleanup such as closing files or returning connections. Catching GeneratorExit and yielding again raises RuntimeError.
yield from iterable does more than for item in iterable: yield item. It forwards send(), throw() and close() straight to the sub-generator, and when the sub-generator finishes with a return value, that value becomes the result of the yield from expression. Its most common uses are splitting a large generator into smaller pieces and flattening recursive data such as trees.
When a generator accepts an iterable and returns a generator, stages chain together, as in server_errors(parse(lines)). Only when the outermost stage is asked for next() does one record travel through every stage, and nothing else is computed yet. The itertools module supplies well-tested parts for these stages: islice slices an iterator, chain joins iterators, groupby groups adjacent equal items, accumulate produces running totals and takewhile stops as soon as its condition fails.
- Prime with next() to the first yield
- send(v): the yield evaluates to v
- throw(e): e is raised at the yield
- close(): GeneratorExit, then finally
All three methods act on the one yield where the generator is paused.
General pattern
def worker():
try:
while True:
received = yield result # out: result, in: what send() passed
finally:
cleanup() # runs on close()
gen = worker(); next(gen) # prime
gen.send(value); gen.throw(SomeError()); gen.close()
def outer(): yield from inner() # delegate, forwarding send/throw
stage3(stage2(stage1(source))) # lazy pipelineThe variable left of yield receives the value sent with send(). finally runs when close() is called. yield from delegates to a sub-generator, and the last line is a pipeline of chained stages.
Example: a running average, flatten, a log pipeline and itertools
The example has four parts. running_average accepts send(), throw() and close(); flatten uses yield from to unpack nested lists; parse and server_errors form a pipeline that handles one log line at a time; and the last lines demonstrate three itertools functions.
import itertools
# 1. send(), throw() and close(): a generator that receives values
def running_average():
total = count = 0
average = None
try:
while True:
try:
value = yield average # pause here, receive a value
except ValueError: # raised inside by throw()
total = count = 0
average = None
continue
total += value
count += 1
average = total / count
finally:
print(" cleanup: running_average closed")
avg = running_average()
next(avg) # prime: run to the first yield
print("1. send:", avg.send(10), avg.send(20), avg.send(60))
print("2. throw ->", avg.throw(ValueError("reset")))
print("3. after reset:", avg.send(5))
avg.close()
# 2. yield from delegates to another iterable (here, recursively)
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print("4. yield from:", list(flatten([1, [2, [3, 4]], 5])))
# 3. A lazy pipeline: each stage pulls one record at a time
LOG = ["GET /a 200", "GET /b 500", "POST /a 201", "GET /c 503", "GET /a 200"]
def parse(lines):
for line in lines:
method, path, status = line.split()
yield method, path, int(status)
def server_errors(records):
return (r for r in records if r[2] >= 500)
print("5. first error:", next(server_errors(parse(LOG))))
# 4. itertools building blocks
paths = sorted(path for _, path, _ in parse(LOG))
print("6. groupby:", {p: len(list(g)) for p, g in itertools.groupby(paths)})
print("7. islice + count:", list(itertools.islice(itertools.count(1, 3), 4)))
print("8. chain:", list(itertools.chain("ab", [1, 2])))Code breakdown
- Line 11
value = yield average # pause here, receive a valueThis hands average out and pauses. When send(10) resumes it, value is 10; the totals update, the average is computed and the loop comes back to this line, yielding 10.0 as send()'s return value. Sending 10, 20 and 60 gives 10.0, 15.0 and 30.0.
- Line 24
next(avg)This runs the new generator to its first yield, which produces None; that value is ignored. Without this line, send(10) on the next line raises a TypeError.
- Line 26-28
print("2. throw ->", avg.throw(ValueError("reset")))The ValueError is raised at the yield; the except clause resets total and count, and continue returns to the yield. That yield produces None, so throw() returns None. close() raises GeneratorExit, which runs the finally block and prints the cleanup line.
- Line 32-37
yield from flatten(item)When an item is a list, flatten calls itself and passes every value it produces straight out. However deep the nesting goes, each level forwards with yield from, giving [1, 2, 3, 4, 5].
- Line 53
print("5. first error:", next(server_errors(parse(LOG))))next() asks server_errors for one record, and server_errors asks parse. "GET /a 200" fails the filter, so parse handles the second line, finds the 500 and stops there. The remaining three lines are never split.
- Line 56-57
itertools.groupby(paths)groupby only groups equal items that sit next to each other, so the paths are sorted first. Unsorted, /a would form three separate groups and the dict would keep only the last count.
1. send: 10.0 15.0 30.0
2. throw -> None
3. after reset: 5.0
cleanup: running_average closed
4. yield from: [1, 2, 3, 4, 5]
5. first error: ('GET', '/b', 500)
6. groupby: {'/a': 3, '/b': 1, '/c': 1}
7. islice + count: [1, 4, 7, 10]
8. chain: ['a', 'b', 1, 2]yield from also captures the sub-generator's return value
A return value inside a generator ends up in StopIteration.value, which for loops ignore. yield from, however, hands that value back as the result of the expression, so a sub-generator can yield items along the way and still report a summary at the end. This is handy when a generator's work is split into parts.
def read_batch(rows):
good = 0
for row in rows:
if row.strip():
good += 1
yield row.strip()
return good # becomes the value of yield from
def read_all(batches):
for i, rows in enumerate(batches, start=1):
count = yield from read_batch(rows)
print(f" batch {i}: {count} rows")
print(list(read_all([["a", " ", "b"], ["c"]])))| itertools function | What it does |
|---|---|
| islice(it, n) | Lazily take the first n items (like it[:n]) |
| chain(a, b) | Iterate several iterables as one |
| groupby(sorted_it, key) | Group adjacent items with the same key |
| accumulate(it) | Produce running totals (or any function) |
| takewhile(pred, it) | Stop at the first item failing pred |
In real projects
Where this shows up in real projects
In data engineering, generator pipelines turn up in ETL scripts: read_rows(file), then clean(rows), validate(rows), batch(rows, 500) and finally a database insert. Each stage is small and testable on its own, and memory use stays flat however large the file is. You can also debug the whole pipeline quickly by taking just the first ten rows with islice.
You rarely call send() and throw() directly in everyday application code, but these mechanisms underpin other tools. contextlib.contextmanager uses a generator's single yield as the middle of a with block, and if the block raises, it passes the exception into the generator with throw(). pytest's yield fixtures treat the code before yield as setup and the code after it as teardown. Python's async/await also grew historically out of the generator send() mechanism.
Common mistakes
Common mistakes
1. Calling send() before priming
avg = running_average(); avg.send(10) raises TypeError: "can't send non-None value to a just-started generator". Call next(avg) or avg.send(None) first. If you keep forgetting, write a tiny helper that creates the generator, calls next() and returns it.
2. Using groupby on unsorted data
groupby is not SQL's GROUP BY; it only looks at adjacent items. Applied directly to ["/a", "/b", "/a"], it yields two /a groups and the counts come out wrong. Sort with the same key first, or use collections.Counter. Also consume each group with list() before moving to the next one, or it will be empty.
3. Feeding one generator to two pipeline stages
Passing records = parse(LOG) to both errors(records) and count(records) means each record taken by one stage is never seen by the other, so both results are incomplete. Call parse(LOG) afresh for each stage, or use itertools.tee, keeping in mind that tee buffers items and can use a lot of memory.
4. Putting cleanup outside finally
If the code that closes a file sits plainly after the while loop, a caller who breaks out of the loop or calls close() never reaches that line. Protect resources inside a generator with a with statement or try/finally, so they are released even when GeneratorExit is raised.
Mini challenge
Mini challenge: an expense pipeline
Pass daily lists of "name,amount" lines through generator stages and print the running totals until they would exceed a budget of 35. Skip malformed lines with a message.
- all_lines(*days) uses yield from to emit every day's lines as one stream
- parse_amounts(lines) yields (name, float) tuples and skips non-numeric lines with "skipped bad line"
- running_totals uses itertools.accumulate, and takewhile keeps totals up to 35
- Use islice to take and print the first two valid Tuesday items
import itertools
MONDAY = ["coffee,3.5", "lunch,12", "oops", "book,18"]
TUESDAY = ["bus,1.5", "dinner,abc", "snack,4"]
def all_lines(*days):
# TODO: delegate to each day's list
...
def parse_amounts(lines):
# TODO: split each line at the first comma (str.partition)
# TODO: yield (name, float(amount)); on ValueError print " skipped bad line: ..."
...
def running_totals(expenses):
# TODO: a generator expression of amounts, passed to itertools.accumulate
...
# TODO: chain the stages, keep totals <= 35 with takewhile, print them
# TODO: print the first two valid Tuesday items using isliceExpected: skipped bad line: 'oops' skipped bad line: 'dinner,abc' totals within budget: [3.5, 15.5, 33.5, 35.0] skipped bad line: 'dinner,abc' first two Tuesday items: [('bus', 1.5), ('snack', 4.0)]
Show hint
"oops".partition(",") returns ("oops", "", ""), and float("") raises ValueError, so a single except also catches lines with no comma. takewhile stops at the first total above 35, so later lines are never parsed.
Show solution
import itertools
MONDAY = ["coffee,3.5", "lunch,12", "oops", "book,18"]
TUESDAY = ["bus,1.5", "dinner,abc", "snack,4"]
def all_lines(*days):
for day in days:
yield from day
def parse_amounts(lines):
for line in lines:
name, _, amount = line.partition(",")
try:
yield name, float(amount)
except ValueError:
print(f" skipped bad line: {line!r}")
def running_totals(expenses):
amounts = (amount for _, amount in expenses)
return itertools.accumulate(amounts)
expenses = parse_amounts(all_lines(MONDAY, TUESDAY))
totals = running_totals(expenses)
under_budget = itertools.takewhile(lambda t: t <= 35, totals)
print("totals within budget:", list(under_budget))
first_two = itertools.islice(parse_amounts(all_lines(TUESDAY)), 2)
print("first two Tuesday items:", list(first_two))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- value = yield x hands out x and receives what send() passes in; prime with next() first.
- throw() raises at the paused yield, and close() raises GeneratorExit so finally cleanup runs.
- yield from delegates to a sub-generator, forwards send and throw, and captures its return value.
- Chained generator stages form a lazy pipeline that moves one record at a time, with itertools supplying islice, chain, groupby, accumulate and takewhile.
Python Documentation — Functional Programming HOWTO — Python Software Foundation