Coroutine Mechanics: Generators to Coroutines
Python coroutines did not drop from the sky. They evolved from generator frame suspension via `yield` to bidirectional communication with `.send()`, culminating in native `async def` which treats suspended frames as first-class asynchronous tasks 🧠🔄.
def echo_routine():
# Yield pauses the frame and returns initial state:
received = yield "AWAITING_INPUT"
# .send() injects value directly into suspended frame:
yield f"PROCESSED: {received} 🚀"
coro = echo_routine()
status = next(coro)
result = coro.send("DATA_PAYLOAD")
print(status)
print(result)
# 16. Coroutine Mechanics: Generators to Coroutines Before `async` and `await` became syntactic sugar in Python 3.5, async programming was powered by raw generator abuse. Calling `yield` suspends the execution frame on the heap, saving local variables until something triggers it to wake up 🛑. ```python def worker(): data = yield "IDLE" yield f"DONE: {data}" w = worker() print(next(w)) # Primes the generator -> "IDLE" print(w.send("PING")) # Injects "PING" into data -> "DONE: PING" ``` ### The Suspension Pipeline 1. **Frame Freezing**: When a generator hits `yield`, CPython saves the execution frame (`f_lasti`, locals, instruction pointer) without destroying the stack. 2. **Value Injection**: Calling `generator.send(val)` awakens the frame, assigns `val` to the yield expression target, and executes until the next yield or return ⚡. 3. **From Generators to Async**: Native coroutines (`async def`) are compiled with code flag `CO_COROUTINE`, enforcing strict event loop driving instead of raw manual iteration. --- ### Interactive Pop-Quiz 🧠#### What does calling `.send(value)` do to a paused Python generator function? - [ ] Resumes the suspended generator frame and makes the current `yield` expression evaluate to `value` ⚡ - [ ] Spawns a new POSIX background OS thread to execute the generator body - [ ] Forces the generator to terminate immediately and emit a StopIteration signal - [ ] Pushes the value into a global Redis pub/sub channel --- ### Practical Challenge 🎯 Define a generator `accumulator()` that starts by yielding `'READY'`. In a loop, it receives numeric values sent via `.send()`, tracks the running sum, and yields that running sum. Prime the generator with `next()`, send `10`, then `25`, and print both results. <details> <summary>Solution</summary> ```python def accumulator(): total = 0 val = yield "READY" while True: total += val val = yield total gen = accumulator() next(gen) print(gen.send(10)) print(gen.send(25)) ``` </details>