Sub topic 15
Two-way communication: send(), throw() and close()
Until now, data has moved in one direction: a generator produces values and the caller consumes them. This chapter covers the three methods that let the caller talk back to a suspended generator: send(), throw() and close().
I assume you know how generator functions pause at yield and resume on next(). You should also be comfortable with try/except/finally and with StopIteration.
yield is an expression
You have used yield as a statement that hands a value out. It is also an expression, so it has a value of its own. In value = yield total, the generator hands total to the caller and pauses. When it resumes, the whole yield total expression evaluates to whatever the caller supplied.
With plain next(gen), the supplied value is always None. gen.send(x) resumes the generator and makes the paused yield evaluate to x.
def running_total():
total = 0
while True:
value = yield total
total += value
acc = running_total()
next(acc) # prime the generator, yields 0
print(acc.send(5)) # 5
print(acc.send(10)) # 15send() does two jobs in a single call. It delivers a value into the generator, and it returns the next value the generator yields. Here, acc.send(5) delivers 5, runs total += value, loops back to yield total, and returns the new total.
Priming
A generator that has not started has no paused yield to receive a value. The first call must therefore be next(gen) or gen.send(None). This runs the body up to the first yield, and it is called priming. Sending anything else first is an error:
import inspect
acc = running_total()
print(inspect.getgeneratorstate(acc)) # GEN_CREATED
try:
acc.send(5)
except TypeError as exc:
print(exc) # can't send non-None value to a just-started generator
next(acc)
print(inspect.getgeneratorstate(acc)) # GEN_SUSPENDEDinspect.getgeneratorstate() reports one of four states: GEN_CREATED, GEN_RUNNING, GEN_SUSPENDED or GEN_CLOSED. It is a useful debugging tool for everything in this chapter.
The order of events
The diagram shows one full exchange. Notice that each call on the caller side corresponds to one pause on the generator side.
Returning a final result
A coroutine-style generator usually runs until the caller signals it is finished. You can use a sentinel value for that signal and report the outcome with return. The returned value travels in StopIteration.value, as covered in the chapter on generator return values.
def averager():
total = 0
count = 0
while True:
value = yield
if value is None:
break
total += value
count += 1
return total / count if count else 0.0
avg = averager()
next(avg)
avg.send(10)
avg.send(20)
try:
avg.send(None)
except StopIteration as stop:
print(stop.value) # 15.0This generator yields no useful values. The bare yield exists only as a place to receive input. When the loop breaks, return ends the generator, and Python raises StopIteration from the send() call with the average attached.
throw(): raising an exception inside the generator
gen.throw(exc) resumes the generator, but instead of making yield produce a value, it makes yield raise exc at the point where the generator is paused. The generator can catch the exception with an ordinary try/except around the yield.
def resilient_total():
total = 0
while True:
try:
value = yield total
except ValueError:
total = 0
continue
total += value
gen = resilient_total()
next(gen)
print(gen.send(5)) # 5
print(gen.send(7)) # 12
print(gen.throw(ValueError)) # 0
print(gen.send(3)) # 3Like send(), throw() returns the next value the generator yields. Here the handler resets the total and the loop reaches yield total again, so throw() returns 0. The caller used an exception as a "reset" command without needing a special sentinel value.
If the generator does not catch the exception, it propagates out of the generator and back to the throw() call. The generator is then finished:
import inspect
def fragile():
yield 1
yield 2
g = fragile()
next(g)
try:
g.throw(RuntimeError("boom"))
except RuntimeError as exc:
print("caught", exc) # caught boom
print(inspect.getgeneratorstate(g)) # GEN_CLOSEDAny uncaught exception inside a generator closes it, whether it came from throw() or from the generator's own code. Further next() calls raise StopIteration.
close(): shutting a generator down
gen.close() raises a special exception called GeneratorExit at the paused yield. The generator is expected to exit, usually by letting the exception propagate through finally blocks that release resources. close() swallows GeneratorExit for you, so the caller sees no error.
def reader():
print("open")
try:
while True:
yield "line"
finally:
print("cleanup")
r = reader()
next(r) # prints: open
r.close() # prints: cleanupWithout close(), the finally block would run only when the generator is garbage collected. On CPython this happens when the last reference disappears. On other implementations the timing is not guaranteed. Closing explicitly gives you deterministic cleanup. A for loop that exits early with break does not close the generator by itself, so call close() or wrap the generator with contextlib.closing.
close() has these rules:
- It is safe to call more than once. Closing a finished or already closed generator does nothing.
- Closing a generator that never started marks it closed without running any of its body.
- It returns
Noneif the generator exits cleanly.
Do not yield after GeneratorExit
If a generator catches GeneratorExit and then yields another value, Python treats it as a refusal to stop and raises RuntimeError:
def stubborn():
try:
yield 1
except GeneratorExit:
yield 2
g = stubborn()
next(g)
try:
g.close()
except RuntimeError as exc:
print(exc) # generator ignored GeneratorExitCatching GeneratorExit is fine for cleanup, but then you must return or re-raise. Avoid a bare except: or except BaseException: around a yield, because it also catches GeneratorExit and tends to produce this error.
Summary of the three methods
| Method | What happens at the paused `yield` | Return value of the call |
|---|---|---|
| `send(x)` | The `yield` expression evaluates to `x` | The next yielded value |
| `throw(exc)` | `exc` is raised at the `yield` | The next yielded value, if the generator handles `exc` |
| `close()` | `GeneratorExit` is raised at the `yield` | `None` |
All three raise StopIteration if the generator finishes while handling the call. send() and throw() on an exhausted generator also raise StopIteration. throw() on an exhausted generator re-raises the thrown exception instead.
Gotchas
- Priming is easy to forget. The
TypeErrorabove is the usual symptom. A small decorator that callsnext()once after creating the generator removes the step. - A generator cannot call itself. If code running inside a generator tries to resume that same generator, Python raises
ValueError: generator already executing. This can occur when a callback invoked from the generator touches the generator object. yield fromforwards all three methods. When an outer generator delegates withyield from inner(),send(),throw()andclose()on the outer generator are passed to the inner one while it is running. This is what makes delegation transparent for two-way generators.- Prefer simpler designs when you can. Two-way generators make control flow harder to follow, because values enter at a
yieldfar from the call site. If you need state plus operations, a class with methods is often clearer. For concurrent programs,async/awaitreplaced this pattern as the standard approach. Knowsend()for reading older code and for small stateful accumulators.
Exercises
Exercise
Write a generator tagger(prefix) that is primed with next(). Each send(text) should return prefix + text. After t = tagger("> ") and next(t), what does t.send("hi") return, and what does next(t) do after that?
Show answer
It returns "> hi". A possible implementation is:
def tagger(prefix):
result = None
while True:
text = yield result
result = prefix + text
next(t) resumes the generator with None as the value of the yield expression, so prefix + text raises TypeError (a string cannot be concatenated with None). Because the exception is uncaught inside the generator, it propagates to the caller and the generator is closed.
Exercise
In the reader() generator from this chapter, what is printed by the following code, and why?
r = reader()
r.close()
print("done")
Show answer
Only "done" is printed. The generator was never started, so close() marks it closed without running any of its body. The "open" line and the finally block never run, because execution never reached the try.