Async Iterators: async for and __aiter__
Async iterators stream data asynchronously without blocking the loop. They implement `__aiter__()` and `async def __anext__()`, raising `StopAsyncIteration` when exhausted 🌊.
import asyncio
class AsyncRange:
def __init__(self, limit):
self.limit = limit
self.count = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.count >= self.limit:
raise StopAsyncIteration
await asyncio.sleep(0.001)
self.count += 1
return self.count
async def main():
return [i async for i in AsyncRange(3)]
print(asyncio.run(main())) # [1, 2, 3] 🌊
# 48. Async Iterators: async for and __aiter__ Async iterators stream data asynchronously without blocking the loop. They implement `__aiter__()` and `async def __anext__()`, raising `StopAsyncIteration` when exhausted 🌊. ```python import asyncio class AsyncRange: def __init__(self, limit): self.limit = limit self.count = 0 def __aiter__(self): return self async def __anext__(self): if self.count >= self.limit: raise StopAsyncIteration await asyncio.sleep(0.001) self.count += 1 return self.count async def main(): return [i async for i in AsyncRange(3)] print(asyncio.run(main())) # [1, 2, 3] 🌊 ``` Async generators (functions using both `async def` and `yield`) provide a shortcut for creating async iterators without writing custom classes! 🌊 --- ### Question Which exception terminates an `async for` loop inside `__anext__`? 🧠- [ ] a. `StopAsyncIteration` 🌊 - [ ] b. `StopIteration` - [ ] c. `GeneratorExit` - [ ] d. `EOFError` --- ### Challenge Write an async generator `async def numbers(n):` yielding `0` to `n - 1` with `await asyncio.sleep(0.001)`. In `async def main():`, collect items via `[x async for x in numbers(3)]`. Run and print result. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def numbers(n): for i in range(n): await asyncio.sleep(0.001) yield i async def main(): return [x async for x in numbers(3)] print(asyncio.run(main())) ``` </details>