asynchronous iterable

In Python, an asynchronous iterable is an object that you can iterate over asynchronously. They work seamlessly with Python’s asynchronous loops and comprehensions, allowing you to iterate over data without halting the execution of your program.

Asynchronous iterables are particularly useful when dealing with I/O-bound operations, such as network requests or file reading.

An asynchronous iterable must implement the .__aiter__() method, which should return an asynchronous iterator.

Example

Here’s a quick example of how you might define and use an asynchronous iterable in Python:

Python async_range.py
import asyncio

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

    async def __aiter__(self):
        for i in self.data:
            await asyncio.sleep(0.5)
            yield i

# Usage
async def main():
    async for i in AsyncRange(0, 10):
        print(i)

asyncio.run(main())

In this example, AsyncRange is an asynchronous iterable that yields numbers from start to end-1. 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 8, 2025 • Reviewed by Leodanis Pozo Ramos