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

Generator Pipelines and Coroutine Patterns

Python GeneratorsđŸŸĸ Free Lesson

Generator Pipelines and Coroutine Patterns

A generator is usually introduced as a memory-saving trick: instead of building a list, you yield values. That is true, but it undersells the design. A generator is a function that can suspend in the middle, hand a value to its caller, and later resume exactly where it stopped, with local variables intact. That single capability supports two very different styles. As an iterator, it produces a stream lazily. As a coroutine, it consumes a stream, running from the inside of a loop that something else drives.

Production code benefits from both. Log processing pipelines chain filters and parsers that never materialize the full input. Stream processors accept pushed messages and accumulate state. The pre-async concurrency patterns in libraries such as Twisted and asyncio's lower layers are exactly this coroutine style, which is why understanding send, throw, and close makes the modern syntax obvious rather than magical.

What You'll Learn

  • 1Compose multiple generators into one lazy pipeline and control its lifetime
  • 2Explain how generators preserve local state across suspensions
  • 3Drive a coroutine with send, throw, and close and capture its return value
  • 4Recognize when a pipeline is truly lazy and when it quietly materializes everything

Pipelines that never hold the whole input

A pipeline is a chain of generators where each stage transforms or filters a stream and passes what remains downward. Because every stage is lazy, the peak memory of the whole chain is one item plus whatever the stages themselves allocate. The composition reads top to bottom, matching the way the data actually flows.

python
import json
from datetime import datetime


def read_lines(path):
    with open(path, encoding="utf-8", errors="replace") as handle:
        for line in handle:
            line = line.strip()
            if line:
                yield line


def parse_events(lines):
    for line in lines:
        try:
            yield json.loads(line)
        except json.JSONDecodeError:
            continue


def within(events, start, end):
    for event in events:
        stamp = event.get("ts")
        if stamp is None:
            continue
        if start <= stamp < end:
            yield event


def pluck(events, key):
    for event in events:
        value = event.get(key)
        if value is not None:
            yield value


def run(path, start, end):
    pipeline = pluck(
        within(parse_events(read_lines(path)), start, end),
        "amount",
    )
    total = 0.0
    count = 0
    for value in pipeline:
        total += value
        count += 1
    return count, total


if __name__ == "__main__":
    start = datetime(2026, 1, 1).timestamp()
    end = datetime(2026, 2, 1).timestamp()
    print(run("events.jsonl", start, end))

Two properties make this trustworthy. First, the file is opened only when the first item is requested, so constructing the pipeline costs nothing. Second, closing the chain closes the innermost generator, which releases the file handle through its own with block. A pipeline abandoned mid-iteration is cleaned up the same way, because garbage collection closes suspended generators and runs their finally blocks.

Delegation with yield from

Once a pipeline grows past three or four stages, the forwarding loops become noise. yield from removes them: it iterates the inner iterable and forwards values outward unchanged, while also wiring up send and throw so the outer caller can talk directly to the innermost generator. It is not merely sugar for a loop; it creates a transparent channel through the delegation chain.

python
def ticker(source, prefix=">"):
    for value in source:
        yield f"{prefix} {value}"


def totals(source):
    running = 0.0
    for value in source:
        running += value
        yield round(running, 2)


def report(source):
    yield from totals(source)


def produce():
    yield 10.0
    yield 2.5
    yield 3.5


for row in report(produce()):
    print(row)

The rule of thumb is simple: if a generator body only loops and yields, replace it with yield from. If it filters, accumulates, or transforms, keep the explicit loop, because the extra work must happen between the yields.

Coroutines: generators that receive

Flipping the direction turns the generator into a consumer. Instead of calling next to pull, the driver calls send to push. The value passed to send becomes the result of the yield expression inside the generator, which is how data enters. Because the generator must be started before the first send can be matched by a yield, a priming step is required: call next(gen) once, or wrap the function so it primes itself.

python
from functools import wraps


def coroutine(fn):
    @wraps(fn)
    def primed(*args, **kwargs):
        gen = fn(*args, **kwargs)
        next(gen)
        return gen
    return primed


@coroutine
def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        try:
            term = yield average
        except StopIteration:
            break
        if term is None:
            break
        total += term
        count += 1
        average = total / count
    return count, average


def feed(gen, values):
    for value in values:
        gen.send(value)
    gen.close()


stream = averager()
feed(stream, [10, 20, 30, 40])
print(stream.gi_frame is None)

throw lets the driver inject an exception at the suspension point, which is how a coroutine cancels or reports an upstream failure, and close raises GeneratorExit at the same point so cleanup blocks run. The return value inside a generator does not produce an empty tuple the way it does in a function; it becomes the value of the StopIteration exception that ends iteration.

Where pipelines quietly become eager

Laziness is easy to lose. Calling list() or sorted() on a stage materializes it, which may be exactly what you want before a second pass, but it defeats the point if it happens inside a hot path. Consuming a generator twice also fails in a confusing way: the second loop simply yields nothing, with no exception to explain why. And a generator that calls another generator without yield from breaks the channel between the outer caller and the inner worker.

There is a subtler trap in pipelines with side effects. Because nothing runs until the consumer pulls, a stage that logs or writes will appear to do its work in the consumer's call stack rather than in the order the code was written. If ordering matters, force evaluation deliberately with deque(maxlen=1) or an explicit list at the boundary where the ordering guarantee is needed.

Resource ownership inside a generator

A generator that opens a file owns it, and the language gives you the machinery to close it: a with block around the loop, and a finally around anything else that must be released. The subtlety is timing. A suspended generator has not run its cleanup yet, so a pipeline that is abandoned halfway through a large file keeps the handle open until the generator object is collected. In a long-running service that pattern leaks descriptors, and the failure arrives as an obscure too-many-open-files error in an unrelated request.

The reliable fix is to drive generators to completion or close them explicitly when you are finished. Closing raises GeneratorExit at the suspension point, which runs the finally block immediately and deterministically. Code that hands a generator to another function should document whether the callee takes ownership; if it does not, the caller closes it in a try and finally of its own.

The same reasoning applies to any other resource a generator might hold: a cursor, a lock, a temporary file, a network stream. If the object would normally be wrapped in a with statement in ordinary code, it needs the same treatment inside a generator, and the cleanup must not depend on garbage collection happening at a convenient moment.

Testing generators and coroutines

Generators are easy to test because they are just values plus an iteration protocol. The cheapest test converts the generator to a list and compares against the expected sequence, which pins ordering and filtering in one assertion. For large or unbounded generators, islice keeps the test bounded and fast, and a sentinel-driven approach lets you verify that the generator stops exactly where it should.

Coroutines need a driver in the test, because send is how data arrives. A small helper that sends every value from a list and then closes the generator keeps the tests readable, and asserting on the return value requires catching StopIteration and reading its value attribute. Testing the exceptional path means calling throw with the error type the real driver would raise, and checking that cleanup ran and the error propagated.

One trap in both cases is shared state between tests: a module-level primed coroutine reused across test functions will carry its accumulated state into the next test and produce failures that depend on ordering. Build a fresh generator inside each test, or wrap construction in a fixture, and the flakiness disappears.

Choosing between pull and push

Pull-style pipelines suit transformation problems: parse, filter, map, aggregate. The consumer controls the rate, which naturally applies backpressure. Push-style coroutines suit accumulation problems: maintain a running state as messages arrive, or implement a mini protocol handler. Once the problem involves several cooperating consumers, scheduling, or true parallelism, move up to asyncio tasks or multiprocessing rather than hand-rolling a scheduler out of coroutines.

Both styles share one discipline: every generator should have a clear lifetime. Open resources in the generator, release them in finally, and always terminate a push-driven coroutine with a close or a terminating sentinel so cleanup actually runs.

Common Mistakes

Iterating the same generator object twice and getting nothing

Fix: Have the producing function return a fresh generator, and treat each generator as single-pass

Forgetting to prime a coroutine before the first send

Fix: Wrap the generator in a priming decorator that calls next once, or call next yourself

Replacing yield from with a plain for loop when the inner generator must receive values

Fix: Use yield from so send and throw reach the innermost generator transparently

Calling list on a stage by accident inside a hot path

Fix: Keep stages lazy and materialize only at the boundary where a second pass is genuinely required

Best Practices

  • Name each pipeline stage after what it does to a single item, not after the pipeline
  • Use yield from whenever a body only forwards values
  • Prime coroutines automatically with a small decorator so callers cannot forget
  • Terminate push-driven coroutines with a sentinel or close so finally blocks run
  • Force ordering deliberately at one boundary instead of spreading materialization through the chain

Interview Questions

Q1: What does send do differently from next?

next resumes the generator and makes the yield expression evaluate to None. send resumes it and makes the yield expression evaluate to the value you passed, which is how data enters a coroutine.

Q2: Why does a generator's return statement not work like a normal return?

The returned value is carried by the StopIteration exception that ends iteration, so it is visible to the driver as StopIteration.value rather than becoming the result of the generator call itself.

Q3: How does a generator-based pipeline apply backpressure?

Because stages are pull-driven, a slow consumer simply stops calling next, and the upstream stages stop producing. Nothing accumulates beyond the item currently in flight.

Key Takeaways

  • Generators suspend with their local state intact, which powers both iteration and coroutines
  • Pipelines stay lazy as long as no stage forces materialization
  • yield from delegates iteration and wires send and throw through to the inner generator
  • Coroutines consume pushed values and must be primed, then closed or terminated
  • Cleanup lives in finally, and garbage collection is what runs it when a generator is abandoned
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