Async Generator Pipeline Compose (Python)
Compose async generators into a pipeline for lazy streaming with backpressure.
Code
import asyncio
async def pipe(source, *transforms):
current = source
for t in transforms:
current = t(current)
async for item in current:
yield item
def amap(fn):
async def inner(source):
async for item in source:
yield fn(item)
return inner
def afilter(pred):
async def inner(source):
async for item in source:
if pred(item):
yield item
return innerHow it works
The snippet is organized around the functions pipe, amap, inner and afilter.
Iteration happens inside for t in transforms — everything outside it runs once. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.
What to watch for
- External dependency:
asyncio— install it before running the snippet.
Using it
The main signature reads def pipe(source, *transforms)
pipe is what another module would consume; nothing else here is load-bearing for callers.
Key statements
async def pipe(source, *transforms):
current = source
for t in transforms:
current = t(current)
async for item in current:
yield item
async def inner(source):
async for item in source:
yield fn(item)
async def inner(source):
async for item in source:
if pred(item):
yield item
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- Yes — `asyncio`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.