Generator send(), throw() & close() Coroutine Basics
1Concept
Generators can receive data from callers via `.send(value)`. Calling `.throw(Exception)` injects an exception at the yield point, and `.close()` raises `GeneratorExit` to terminate the generator safely.
2Architecture Diagram
Caller ---> .send("Data") ---> [ yield resumes with "Data" ] ---> Computes next state3Code Example
Python 3.12
def accumulator():
total = 0
while True:
val = yield total
if val is None:
break
total += val
acc = accumulator()
next(acc) # Prime the generator to first yield point
print(f"Accumulated: {acc.send(10)}")
print(f"Accumulated: {acc.send(25)}")
acc.close()
print("Accumulator coroutine closed safely.")4Expected Output
Accumulated: 10 Accumulated: 35 Accumulator coroutine closed safely.
5Key Takeaways
- ✓Generators must be 'primed' with `next(gen)` or `gen.send(None)` before sending values.
- ✓`GeneratorExit` exception is caught inside generators to execute resource cleanup.
- ✓This generator co-routine mechanic was the historical precursor to modern `async`/`await` in Python.