Advertisement

Async Generators & Async Context Managers interview questions and answers

15 Async Generators & Async Context Managers interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How do async generators interact with asyncio.Queue to implement a producer-consumer pattern across separate tasks?

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?
Concurrency (asyncio/threading/multiprocessing)
Q12 Advanced Save

How would you implement an async context manager that also supports being used as a decorator, similar to contextlib.contextmanager's decorator support?

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.
from contextlib import asynccontextmanager

@asynccontextmanager
async def timed():
    start = time.monotonic()
    try:
        yield
    finally:
        print(f"Took {time.monotonic() - start:.2f}s")

@timed()
async def slow_operation():
    await asyncio.sleep(1)
Real-world example
Building a reusable async timing or logging decorator that can ALSO be used explicitly as an 'async with' block when needed.
Likely follow-ups
  • What's the underlying mechanism that lets a single @asynccontextmanager-decorated function support both usages?
Decorators
Q13 Advanced Save

How do you properly propagate cancellation into an async generator when the consuming task is cancelled mid-iteration?

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?
Exception Handling
Q14 Advanced Save

How would you implement a 'fan-out, fan-in' pattern using multiple async generators consumed concurrently and merged into one stream?

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?
Concurrency (asyncio/threading/multiprocessing)
Q15 Advanced Save

How do you correctly test async generators and async context managers using pytest and pytest-asyncio?

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?
Testing (pytest)

Showing 11–15 of 15