Python › Async Generators & Async Context Managers

What is an async generator, and how does it differ from a regular generator?

Beginner

Answer

An async generator is a function defined with 'async def' that uses 'yield' inside it, producing an object supporting the asynchronous iteration protocol (__anext__) instead of the regular one — it lets each item be produced after an 'await', unlike a regular generator which is fully synchronous.
async def fetch_pages():
    for i in range(3):
        await asyncio.sleep(0.1)  # simulate async work
        yield f"page-{i}"
Real-world example Streaming paginated API results one page at a time, awaiting each network call before yielding the next page.

Common follow-ups: How do you actually consume an async generator's yielded values?