← Back to Python, page 4

python-0067 · Hard senior

How do generators support send(), throw() and close(), and what is a coroutine-style generator used for?

send(value) resumes a generator and makes the paused yield expression evaluate to that value, so a generator can receive data as well as produce it. throw() raises an exception at the paused yield, and close() raises GeneratorExit so finally blocks run. These enable pipeline stages and running calculations, though async def has replaced generator-based coroutines for concurrency.

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 input

The 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