🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Generator Pipelines with send() and yield from

Python GeneratorsđŸŸĸ Free Lesson

Generator Pipelines with send() and yield from

A generator is a function that remembers where it stopped, and that single property is enough to build a streaming ETL stage out of ordinary control flow. Chained generators process one record at a time, so a file the size of your disk costs the memory of a single line, and each stage stays independently testable. The advanced surface ” yield from, send, throw, close ” is where pipelines stop being a curiosity and become a legitimate alternative to a message queue for in-process work.

What You'll Learn

  • 1Compose multi-stage generator pipelines that stream instead of materialise
  • 2Explain what yield from delegates and how it returns a value
  • 3Drive a generator from the outside with send, throw, and close
  • 4Guarantee cleanup with try, finally, and GeneratorExit

A pipeline is a chain of lazy transformations

Each stage does one job, takes an iterable, and yields results. Composition is just nesting the calls: the output of the reader feeds the filter, whose output feeds the parser. Nothing runs until something iterates, which means opening the file, the parsing, and the final aggregation all happen inside a single loop rather than in three passes over the data.

python
import csv
from typing import Iterable, Iterator


def read_rows(path: str) -> Iterator[list[str]]:
    with open(path, newline="") as handle:
        yield from csv.reader(handle)


def skip_comments(rows: Iterable[list[str]]) -> Iterator[list[str]]:
    for row in rows:
        if row and not row[0].lstrip().startswith("#"):
            yield row


def to_records(rows: Iterable[list[str]]) -> Iterator[dict]:
    header = None
    for row in rows:
        if header is None:
            header = row
            continue
        yield dict(zip(header, row))


def active_emails(records: Iterable[dict]) -> Iterator[str]:
    for record in records:
        if record.get("status") == "active" and record.get("email"):
            yield record["email"].strip().lower()


pipeline = active_emails(to_records(skip_comments(read_rows("users.csv"))))
for address in pipeline:
    print(address)

Two properties make this worth doing. Stages are reusable ” to_records works with any source of string lists, including a socket or a test fixture ” and failure stays local: a malformed row raises at the exact stage that could not handle it, with the line number still meaningful. The cost is that generators are single-use; iterating the pipeline twice means building it twice.

What yield from actually does

yield from is not syntactic sugar for a loop. It delegates iteration to a subgenerator and, crucially, pipes values in both directions: values sent into the outer generator arrive directly at the inner one, and the value the inner generator returns becomes the value of the yield from expression.

python
def inner():
    received = yield "ready"
    print(f"inner got {received}")
    return 41


def outer():
    first = yield from inner()
    second = first + 1
    result = yield second
    print(f"outer got {result}")
    return "done"


gen = outer()
print(next(gen))        # ready
print(gen.send(10))     # inner got 10 -> 42
try:
    gen.send("bye")
except StopIteration as stop:
    print(stop.value)   # done

Without delegation you would hand-roll send forwarding, exception propagation, and close fan-out in every wrapper ” the exact code PEP 380 removed. Delegation also composes: a pipeline stage built from three subgenerators behaves, to its consumer, like one generator, and throw reaches whichever inner frame is currently executing.

Driving a generator from the outside

send resumes the generator with a value delivered to the pending yield, throw raises an exception at that same point, and close raises GeneratorExit so finally blocks run. Together they turn a generator into a coroutine that processes a stream and can be interrupted.

python
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        try:
            term = yield average
        except ValueError:
            print("rejected a bad reading")
            continue
        if term is None:
            break
        total += term
        count += 1
        average = total / count
    return count, average


stream = averager()
next(stream)                 # prime: run to the first yield
print(stream.send(10))       # 10.0
print(stream.send(30))       # 20.0
stream.throw(ValueError)     # handled inside the loop
print(stream.send(50))       # 30.0
stream.close()

The priming call is the step people forget: a generator body does not run until the first next, so the first send before any next raises TypeError. Since Python 3.8 these generator-based coroutines are officially superseded by async/await for scheduling work; they remain valuable for data pipelines, where the generator is the stream rather than a task waiting on I/O.

Cleanup is part of the contract

When a consumer abandons a pipeline, Python throws GeneratorExit into the suspended frame. If the generator yields again after that, it is an error; if it swallows the exception, resources leak. The safe shape is always try, finally, and no yield in the cleanup path.

python
def watch(path: str):
    handle = open(path)
    try:
        for line in handle:
            yield line.strip()
    finally:
        handle.close()
        print("closed")


stream = watch("data.txt")
next(stream)
stream.close()   # runs the finally block immediately

The with open(...) form does this for you, which is why real pipelines wrap file and network handles in context managers rather than closing them by hand. The rule generalises: any generator holding a lock, a cursor, or a subscription must release it in finally, because close is the only guarantee you get when a for loop breaks early or an exception unwinds the stack.

Testing laziness instead of assuming it

Because every stage accepts an iterable, a unit test is a list literal and nothing more: feed to_records a few rows of strings, assert the dictionaries that come out, and you are done. The behaviour worth testing explicitly is when work happens, because laziness is the whole reason to choose a pipeline and it silently disappears if someone adds a list(...) inside a stage.

python
import itertools


def take(n, iterable):
    return list(itertools.islice(iterable, n))


pulled = []


def source():
    for value in range(5):
        pulled.append(value)
        yield value


def double(rows):
    for row in rows:
        yield row * 2


stream = double(source())
print(pulled)          # [] — building the pipeline did no work
print(next(stream))    # 0
print(pulled)          # [0] — exactly one row was pulled
print(take(2, stream)) # [2, 4]
print(pulled)          # [0, 1, 2]

Assertions of this shape catch the classic regression where a refactor materialises an intermediate collection and the pipeline quietly starts needing memory proportional to the input. The same probe doubles as a debugging tool: when a stage misbehaves, wrap the source in a counter like pulled and you can see exactly how far the consumer read before the error appeared. Avoid itertools.tee as a debugging aid — it buffers everything one branch did not consume, which turns your memory-safe pipeline back into a list with a better name.

Where laziness stops paying

Laziness is not free. Every yield is a frame suspension and resumption, so a pipeline that produces millions of trivial rows can lose to a vectorised batch operation, and a generator that yields one item at a time through three stages pays that cost three times per record.

SituationPrefer a generator pipelinePrefer materialising
File larger than comfortable memoryAlwaysNever
Each row needs real parsing or I/OYes, the work dominates”
Simple numeric transform over a list”List comprehension or NumPy
Results consumed more than onceCache into a list firstYes
Stages run concurrentlyHand off to a queue”

Measure both shapes with timeit on a realistic slice before committing. The pattern that usually wins for log-scale data is hybrid: stream through the expensive stages, then batch the cheap tail into chunks so downstream code sees a list of a thousand rows rather than a million single-item yields.

When a pipeline should become a class

Generators hit a wall when the stream must be resumable, restartable, or shared. A generator object is single-use and tied to one function, so a cursor that a caller may seek, a source two consumers must read independently, or a stream that survives a reconnect belongs in a class implementing __iter__ and __next__. The iterator protocol gives you restartability for free: iter(obj) can return a fresh generator each time, while the object keeps the configuration.

The same reasoning applies to infinite streams ” a ticker, a random walk, a replay log. Express the step as a generator, but own the state on the object, so a consumer can stop, resume, and inspect it without keeping a naked generator reference alive.

Common Mistakes

Calling send before the generator has been primed with next

Fix: Advance to the first yield once before sending, or use a helper decorator that primes the coroutine for you

Yielding inside a finally block of a closing generator

Fix: Release resources without yielding after GeneratorExit; a yield during shutdown raises RuntimeError

Reusing a consumed pipeline for a second pass

Fix: Build the pipeline inside a function or a class that returns a fresh generator from each call to iter

Assuming laziness is always faster than a list

Fix: Benchmark: for small in-memory data the yield overhead loses to a comprehension or a vectorised operation

Best Practices

  • Give every stage a single responsibility and type its input and output as Iterable and Iterator
  • Close or context-manage any resource a generator touches, and release it in finally
  • Use yield from for delegation instead of hand-writing send and throw forwarding
  • Keep the expensive stages lazy and batch the cheap tail so downstream code gets lists, not single rows
  • Test a stage by feeding it a plain list; if it only works with a live file handle, the abstraction is wrong

Interview Questions

Q1: What does yield from return?

The value the subgenerator passed to return, delivered through StopIteration.value. It also forwards sent values and thrown exceptions straight to the inner frame, which is why it replaces manual delegation.

Q2: Why must a generator be primed before send?

The body has not executed yet, so there is no suspended yield to receive the value. Calling send immediately raises TypeError; one next call advances the frame to the first yield.

Q3: What happens when a generator is garbage collected without being exhausted?

CPython raises GeneratorExit at the suspended point, running finally blocks. Relying on this is fragile in other implementations, so explicit close or a context manager is the safe pattern.

Q4: Pipeline or list comprehension?

A pipeline when data exceeds memory, when stages involve I/O, or when results are consumed once. A comprehension when the data fits comfortably and the transform is cheap, because suspending frames costs more than building the list.

Key Takeaways

  • Pipelines stream one record at a time, keep stages independently testable, and cost a single row of memory
  • yield from delegates in both directions: sent values reach the inner generator and its return value becomes the expression result
  • send, throw, and close drive a generator from outside, which is how data streams become interruptible
  • Cleanup belongs in finally, because close and garbage collection are the only ways an abandoned generator ever runs it
  • Laziness has overhead; batch the cheap stages and benchmark against the materialised version
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement