Sub topic 15
Two-way communication: send(), throw() and close()
This chapter assumes you know how a generator pauses at yield and resumes on next(). It also assumes you are comfortable with try/except/finally. So far data has flowed one way, from the generator to the caller. Generators can also receive values and exceptions while they are suspended.
yield is an expression
A yield can produce a value for the caller. It can also evaluate to a value that the caller sends back in. send(value) resumes the generator and makes the paused yield expression evaluate to value. It then runs to the next yield and returns the value yielded there.
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)) # 15The first call must be next(acc) or acc.send(None). A new generator is not paused at a yield yet, so there is nothing to receive the value. Calling send(5) first raises TypeError. Running up to the first yield is called priming.
throw(): raising an exception inside
throw(exc) resumes the generator by raising exc at the paused yield. The generator can catch it with an ordinary try/except and carry on. If it does, throw() returns the next yielded value. If it does not catch the exception, the exception propagates back to the caller and the generator is finished.
def resilient_total():
total = 0
while True:
try:
value = yield total
total += value
except ValueError:
print("bad value, resetting")
total = 0
acc = resilient_total()
next(acc)
print(acc.send(5)) # 5
print(acc.throw(ValueError)) # prints "bad value, resetting", then 0
print(acc.send(2)) # 2This lets a caller signal events such as "stop reading, the connection dropped" without inventing a special value to send.
close(): shutting down cleanly
close() raises GeneratorExit at the paused yield. Use try/finally in the generator to release resources. After close() the generator is finished, and any further next() raises StopIteration.
def worker():
try:
while True:
item = yield
print("got", item)
finally:
print("cleanup")
w = worker()
next(w)
w.send("a") # prints "got a"
w.close() # prints "cleanup"Common errors
| Mistake | Result |
|---|---|
| Calling `send(5)` on a new generator | `TypeError` about sending a non-None value to a just-started generator |
| Calling `send()` after the generator finished | `StopIteration` |
| Yielding inside `except GeneratorExit` | `RuntimeError` |
| Forgetting that `send()` returns the next yielded value | Output seems shifted by one step |
Exercise
In running_total(), what does acc.send(10) return if the previous call was acc.send(5), and why does the first call have to be next(acc)?
Show answer
It returns 15. send(10) resumes the paused yield total, which evaluates to 10. The generator adds it to the total (5 + 10) and then pauses at the next yield total, which returns 15. The first call must be next(acc) because a new generator is not yet paused at a yield, so it cannot receive a value. Priming runs it to the first yield.