An async iterator implements __aiter__ and async __anext__ so async for can consume values that may require waiting.
Understanding the Concept
An async iterator implements __aiter__ and async __anext__ so async for can consume values that may require waiting. Exhaustion is reported by StopAsyncIteration.
Async iteration is useful for streaming I/O; do not collect every item if the source may be unbounded.
How the event loop makes progress
When a coroutine reaches await, it may suspend so another ready Task can execute. This scheduling is cooperative: blocking operations that do not yield hold up every coroutine sharing the event loop. Assign ownership of background tasks, put timeouts around operations that may wait, and release resources on cancellation.
An async function does not automatically use several CPU cores. Use async-compatible I/O for waiting tasks and executors or separate processes for blocking or CPU-heavy work when appropriate.
Worked Example
Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.
import asyncio
class Counter:
def __init__(self, limit):
self.current = 0
self.limit = limit
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.limit:
raise StopAsyncIteration
await asyncio.sleep(0)
self.current += 1
return self.current
async def main():
async for value in Counter(3):
print(value)
asyncio.run(main())
Walkthrough: What Each Part Does
- The imports make asyncio available. These are standard-library building blocks unless the example explicitly names an external tool.
- The definition Counter, main creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
- Each await is a suspension point. When the awaited operation is not ready, the loop can schedule other tasks instead of blocking the entire thread.
- The loop repeats one well-defined unit of work. Check termination, ordering and whether an item may be processed more than once.
- The coordination call waits for a result or a completion condition. Predict what would happen if the worker failed or never became ready.
This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.
Example Output
1
2
3
The output above was captured by running the example in the available Python environment. The order of concurrent events, durations and platform-dependent values can legitimately differ on your computer.
Important Behavior and Edge Cases
Raising StopIteration instead of StopAsyncIteration or using ordinary for with an async iterator.
Async iteration is useful for streaming I/O; do not collect every item if the source may be unbounded.
Practice Exercise
Write an async iterator that emits three timestamp-free status messages.
Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.
Further reading: official documentation and API reference.
Common Beginner Mistakes
- Raising StopIteration instead of StopAsyncIteration or using ordinary for with an async iterator.
- Calling a blocking function inside the event loop, or creating tasks without awaiting, cancelling or owning them.
Key Takeaways
- An async iterator implements __aiter__ and async __anext__ so async for can consume values that may require waiting.
- Async iteration is useful for streaming I/O; do not collect every item if the source may be unbounded.
- Practice: Write an async iterator that emits three timestamp-free status messages.