Mastery
Mastery/Python/B. Iteration & generators
T2 · intermediate depth

yield from, delegation, and generator send()/throw()/close()

yield from subgen delegates to another generator transparently: values it yields pass straight through, send()/throw() calls get forwarded into it, and its return value becomes the result of the yield from expression itself. Generators are more than a yield-only iterator: send(value) resumes with value as the result of the paused yield, throw(exc) raises an exception at the paused point, and close() injects a GeneratorExit.

python
def inner_gen():
    print("  inner: starting")
    x = yield 1
    print("  inner: received", x)
    yield 2
    print("  inner: finishing")
    return "inner done"

def outer_gen():
    result = yield from inner_gen()   # delegates -- outer_gen barely knows inner_gen exists
    print("  outer: inner's return value was", repr(result))
    yield 3

g = outer_gen()
print(next(g))
print(g.send("hello"))
print(next(g))

send, throw, and close on a bare generator (no delegation), showing the full two-way communication protocol:

python
def echo():
    while True:
        try:
            received = yield
            print("  echo received:", received)
        except ValueError as e:
            print("  echo caught a thrown exception:", e)

e = echo()
next(e)               # prime it -- must advance to the first yield before send() works
e.send("hi")
e.throw(ValueError("injected error"))   # raises INSIDE the generator, at the paused yield
e.close()              # injects GeneratorExit
try:
    e.send("after close")
except StopIteration:
    print("sending to a closed generator raises StopIteration")

Interview angle

send/throw/close are rarely tested directly, but yield from shows up whenever a candidate is asked to compose generators — "flatten these nested generators without a manual loop" is a natural exercise where yield from is the clean answer, and knowing it also forwards send/throw and captures the sub-generator's return value shows real depth beyond "it's like a nested for-loop."

In the industry

yield from is the standard tool for generator composition and delegation — breaking a large generator into smaller, reusable pieces without manually re-yielding each value. The full send/throw two-way protocol is genuinely rare in typical application code; it's foundational to how asyncio coroutines worked before async/await became the syntax, so understanding it helps when reading older async code or asyncio internals, even though almost nobody writes raw send/throw generators directly anymore.