Python › Async Generators & Async Context Managers

How would you implement timeout handling for an async generator's individual yields, so a stalled source doesn't hang the consumer forever?

Advanced

Answer

Wrap each call to the generator's __anext__() in asyncio.wait_for() with a timeout, catching asyncio.TimeoutError if a specific item takes too long to arrive — since 'async for' itself doesn't provide a built-in per-item timeout mechanism.
async def with_timeout(source, timeout):
    it = source.__aiter__()
    while True:
        try:
            yield await asyncio.wait_for(it.__anext__(), timeout)
        except StopAsyncIteration:
            break

async def main():
    async for item in with_timeout(slow_stream(), timeout=2.0):
        print(item)
Real-world example Cutting off a stalled network stream or SSE connection after a set idle period, instead of hanging indefinitely.

Common follow-ups: What exception does asyncio.wait_for() raise when the timeout expires, and how do you distinguish it from StopAsyncIteration?