Full answer
python
def running_average():
total = count = 0
average = None
try:
while True:
value = yield average
total += value
count += 1
average = total / count
finally:
print("closed after", count, "values")
avg = running_average()
next(avg)
print(avg.send(10), avg.send(20), avg.send(60))
avg.close()
def worker():
try:
yield "ready"
except ValueError as e:
yield f"handled {e}"
w = worker()
print(next(w), w.throw(ValueError("bad input")))Output:
text
10.0 15.0 30.0
closed after 3 values
ready handled bad inputThe first next() primes the generator so it pauses at its first yield. Each send delivers a value and receives the updated average: 10.0, 15.0 and 30.0. close() triggers the finally block. throw raises inside the generator at the paused point, where it is caught and a new value is yielded. Forgetting to prime the generator raises TypeError: can't send non-None value to a just-started generator.
python
def running_average():
total = count = 0
average = None
try:
while True:
value = yield average
total += value
count += 1
average = total / count
finally:
print("closed after", count, "values")
avg = running_average()
next(avg)
print(avg.send(10), avg.send(20), avg.send(60))
avg.close()
def worker():
try:
yield "ready"
except ValueError as e:
yield f"handled {e}"
w = worker()
print(next(w), w.throw(ValueError("bad input")))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- send passes values into a paused generator
- Prime with next() first
- throw raises at the yield
- close runs finally blocks
- async def replaced generator coroutines
Common mistakes
- Sending before priming
- Swallowing GeneratorExit
Follow-ups
- What does yield from add to send()?
- How do async generators differ?
Tips
- Show priming