Build an Async Iterator
Advanced · Write the code · from Python Async/Await: Write Non-Blocking Code from Scratch
From the lesson: Python Async/Await: Write Non-Blocking Code from Scratch
Imagine you're a chef in a busy kitchen. You don't stand and watch the oven for 20 minutes while your pasta boils on another burner. Instead, you start the oven, move to the pasta, then check the salad -- all without waiting idle. That's exactly what asynchronous programming does for your code.
Read the lessonCreate a class called Countdown that implements the async iterator protocol. It should:
1. Accept a start value in __init__
2. Implement __aiter__ returning self
3. Implement __anext__ that counts down from start to 1, raising StopAsyncIteration when done
After the class, print the string Countdown ready to confirm your class is defined.
What Check runs
Your code runs first, then each of these lines. The output must match exactly.
| Runs | Expected output |
|---|---|
| c = Countdown(3) print(hasattr(c, "__aiter__")) print(hasattr(c, "__anext__")) | Countdown ready True True |
| async def collect(counter): return [n async for n in counter] print(await collect(Countdown(3))) | Countdown ready [3, 2, 1] |
More Async and Await exercises
- Define a CoroutineAdvanced
- Predict the Coroutine OutputAdvanced
- Fix the Async BugAdvanced
- Gather Concurrent ResultsAdvanced
- Refactor to Async PatternAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz