asynchronous iterator

In Python, an asynchronous iterator is an object that allows you to traverse asynchronous iterables using async for loops.

This type of iterator is particularly useful when you need to iterate over asynchronously generated data.

An asynchronous iterator must implement the .__aiter__() and .__anext__() special methods. The .__aiter__() method will return the iterator object itself, while the .__anext__() method must return an awaitable object. When the data is over, .__anext__() must raise a StopAsyncIteration exception.

Example

Here’s an example of an asynchronous iterator that generates numbers with a delay:

Python async_range.py
import asyncio

class AsyncRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.start < self.end:
            await asyncio.sleep(0.5)
            value = self.start
            self.start += 1
            return value
        else:
            raise StopAsyncIteration
# Usage
async def main():
    async for i in AsyncRange(0, 5):
        print(i)

asyncio.run(main())

In this example, AsyncRange is an asynchronous iterator that generates numbers from star to end-1. The asyncio.sleep() simulates an asynchronous task. The main() function demonstrates how to iterate over it using async for.

Tutorial

Asynchronous Iterators and Iterables in Python

In this tutorial, you'll learn how to create and use asynchronous iterators and iterables in Python. You'll explore their syntax and structure and discover how they can be leveraged to handle asynchronous operations more efficiently.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 9, 2025 • Reviewed by Leodanis Pozo Ramos