async for iterates over async iterables. async with manages async context managers.
1import asyncio23# Async iterator4class AsyncCounter:5 def __init__(self, stop):6 self.stop = stop7 self.current = 089 def __aiter__(self):10 return self1112 async def __anext__(self):13 if self.current >= self.stop:14 raise StopAsyncIteration15 await asyncio.sleep(0.1) # Simulate async work16 self.current += 117 return self.current1819async def main():20 async for num in AsyncCounter(5):21 print(num) # 1, 2, 3, 4, 52223asyncio.run(main())
Common use cases: