A producer task pushes items into an asyncio.Queue with await queue.put(), while a consumer wraps queue.get() in an async generator (looping until a sentinel value signals completion) — decoupling the producer and consumer into independently-scheduled tasks, with the queue providing natural backpressure via its optional maxsize.
async def consume(queue):
while True:
item = await queue.get()
if item is None: # sentinel signals completion
break
yield item
async def producer(queue):
for i in range(5):
await queue.put(i)
await queue.put(None)
Real-world example
Decoupling a fast data producer task from a slower consumer task, using a bounded queue to apply backpressure automatically.
Likely follow-ups
How does setting a maxsize on the asyncio.Queue create backpressure on the producer?
contextlib.AsyncContextDecorator (or simply using @asynccontextmanager, which already supports this) lets the same async context manager be applied either with 'async with' OR as a decorator on an async function, automatically wrapping the entire function call in the context manager's enter/exit logic.
When the task running an 'async for' loop is cancelled, asyncio.CancelledError is raised at the current 'await' point inside the generator (typically at the yield or an internal await) — a try/finally inside the generator still runs its cleanup correctly, since CancelledError propagates through the generator's frame just like any other exception.
async def stream_data():
try:
while True:
data = await fetch_next_chunk()
yield data
except asyncio.CancelledError:
print("Stream cancelled, cleaning up")
raise # re-raise to properly propagate cancellation
finally:
await cleanup_connection()
Real-world example
Ensuring a streaming data pipeline cleans up its network connection correctly when the consuming task is cancelled (e.g., a request timeout).
Likely follow-ups
Why is it important to re-raise CancelledError rather than swallowing it inside the except block?
Launch multiple async generators as separate tasks pushing their results into a shared asyncio.Queue (or use asyncio.as_completed on wrapped tasks), then consume the merged queue with a single async generator — producing a unified stream where results appear in whatever order they actually complete, not in source order.
async def merge(*sources):
queue = asyncio.Queue()
async def pump(source):
async for item in source:
await queue.put(item)
await queue.put(_DONE)
tasks = [asyncio.create_task(pump(s)) for s in sources]
remaining = len(tasks)
while remaining:
item = await queue.get()
if item is _DONE:
remaining -= 1
else:
yield item
Real-world example
Merging live updates from multiple independent async data sources (e.g., several websocket feeds) into one unified event stream.
Likely follow-ups
What sentinel or signaling mechanism would you use to know when ALL source generators have finished?
Mark the test function with @pytest.mark.asyncio (or use pytest-asyncio's auto mode), then use 'async for' or 'async with' directly inside the async test function exactly as you would in application code — assertions can be made on collected values or on side effects observed during/after iteration.
import pytest
@pytest.mark.asyncio
async def test_fetch_pages():
results = [page async for page in fetch_pages()]
assert results == ["page-0", "page-1", "page-2"]
@pytest.mark.asyncio
async def test_async_connection():
async with async_connection() as conn:
assert conn.is_open
Real-world example
Writing reliable unit tests for an async data pipeline or async resource manager as part of a CI test suite.
Likely follow-ups
What pytest-asyncio configuration option controls whether every async test needs the explicit @pytest.mark.asyncio decorator?