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.
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:
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")