Back
+20 XP
Concept

Async Iterators & Async Generators

Asynchronous iterators stream continuous data across time without hoarding gigabytes in memory. Implementing `__aiter__` and `__anext__` (or defining an `async def` function with `yield`) lets you consume real-time chunked streams via `async for` 🌊🔄.

python
import asyncio

# Async generator function:
async def tick_stream(count):
    for i in range(count):
        await asyncio.sleep(0.01)
        yield f"TICK_{i} ⏱️"

async def main():
    # Consuming asynchronously:
    async for tick in tick_stream(3):
        print(tick)

asyncio.run(main())

# 26. Async Iterators & Async Generators Synchronous iterators (`for item in iterable:`) expect values to exist in memory immediately. When streaming SSE events, real-time WebSocket frames, or database cursor batches, each chunk arrives over the network after an asynchronous delay 🛑. ```python import asyncio async def log_streamer(): while True: line = await read_line_from_socket() if not line: break yield line ``` ### The Async Iterator Protocol 1. **`__aiter__()`**: Must return an object implementing `__anext__()` (usually `self`). Unlike `__anext__`, `__aiter__` itself is synchronous. 2. **`__anext__()`**: Must be an awaitable coroutine returning the next value. 3. **`StopAsyncIteration`**: Raising `StopIteration` inside an async iterator will cause CPython runtime warnings or crashes; you MUST raise `StopAsyncIteration` to terminate an `async for` loop cleanly 🛑. --- ### Interactive Pop-Quiz 🧠 #### Which exception must an async iterator raise inside `__anext__()` to signal that stream iteration has terminated? - [ ] `StopAsyncIteration` 🛑 - [ ] `StopIteration` - [ ] `asyncio.CancelledError` - [ ] `GeneratorExit` --- ### Practical Challenge 🎯 Implement a class `AsyncCountdown` with `__init__(self, start)`, `__aiter__(self)`, and an `async def __anext__(self)` method that decrements down to 0, raises `StopAsyncIteration` when reaching below 0, and sleeps 0.005s per tick. Collect the numbers using `[x async for x in AsyncCountdown(3)]` and print them. <details> <summary>Solution</summary> ```python import asyncio class AsyncCountdown: def __init__(self, start): self.val = start def __aiter__(self): return self async def __anext__(self): if self.val < 0: raise StopAsyncIteration current = self.val self.val -= 1 await asyncio.sleep(0.005) return current async def main(): res = [x async for x in AsyncCountdown(3)] print(res) asyncio.run(main()) ``` </details>

Checkpoint

Which exception must an async iterator raise inside `__anext__()` to signal that stream iteration has terminated? 🧠

Practice

Implement a class `AsyncCountdown` with `__init__(self, start)`, `__aiter__(self)`, and an `async def __anext__(self)` method that decrements down to 0, raises `StopAsyncIteration` when reaching below 0, and sleeps 0.005s per tick. Collect the numbers using `[x async for x in AsyncCountdown(3)]` and print them. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks