How would you implement a coroutine-style generator-based pipeline (the classic pre-async/await pattern) using multiple chained 'send()'-driven generators?
Short answer
Build a chain of 'consumer' generators, each primed with next() and receiving values via .send() from an upstream stage, forwarding processed results downstream — this classic pattern (popularized by David Beazley's coroutine talks) predates async/await and demonstrates how…
Advertisement
AModel answer
Build a chain of 'consumer' generators, each primed with next() and receiving values via .send() from an upstream stage, forwarding processed results downstream — this classic pattern (popularized by David Beazley's coroutine talks) predates async/await and demonstrates how generators alone can implement a full data pipeline with backpressure-free pushing.
def printer():
while True:
value = yield
print(f"Got: {value}")
def filter_even(target):
while True:
value = yield
if value % 2 == 0:
target.send(value)
p = printer(); next(p)
f = filter_even(p); next(f)
for i in range(5):
f.send(i) # sends 0, 2, 4 through to the printerReal-world example
Understanding the historical generator-based coroutine pattern that directly inspired and predates Python's async/await syntax.
Likely follow-ups
- Why did Python eventually introduce dedicated async/await syntax instead of relying entirely on this generator-based coroutine pattern?
Related topics