Advertisement
Beginner Python, Async Generators & Async Context Managers

How do you consume an async generator using 'async for'?

Short answer

'async for' is the asynchronous equivalent of a regular 'for' loop — it awaits each call to the generator's __anext__() method, pausing until the next value is ready, and must itself be used inside an 'async def' function.

Save Python mock interview
Advertisement
AModel answer
'async for' is the asynchronous equivalent of a regular 'for' loop — it awaits each call to the generator's __anext__() method, pausing until the next value is ready, and must itself be used inside an 'async def' function.
async def main():
    async for page in fetch_pages():
        print(page)

asyncio.run(main())
Real-world example
Processing streamed results from an async API client one item at a time as they arrive.
Likely follow-ups
  • Can 'async for' be used outside of an async function?
Related topics