Async generator combines async def and yield. Produces values asynchronously.
1import asyncio23async def async_range(start, stop):4 current = start5 while current < stop:6 await asyncio.sleep(0.1) # Async operation7 yield current8 current += 1910async def main():11 async for num in async_range(0, 5):12 print(num) # 0, 1, 2, 3, 41314asyncio.run(main())
Async generator expression:
1async def fetch(url):2 await asyncio.sleep(1)3 return url45# Async generator expression6async_gen = (await fetch(url) for url in urls)78# With comprehension9results = [await fetch(url) async for url in urls]
Use cases: