Python › Async Generators & Async Context Managers
How do you consume an async generator using 'async for'?
BeginnerAnswer
'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.