asynchronous generator iterator

In Python, an asynchronous generator iterator is an iterator returned by a function that combines the async def and yield keywords. These generators produce a series of values over time when each value is the result of some asynchronous operation, such as I/O-bound tasks.

Asynchronous generator iterators allow you to iterate over data that is produced asynchronously. Instead of blocking the execution while waiting for the data to become available, these iterators enable your program to perform other tasks in the meantime. This can lead to more efficient and responsive applications, particularly in scenarios involving network operations or other time-consuming tasks.

Example

Here’s a example of how to use an asynchronous generator iterator:

Python
>>> import asyncio

>>> async def async_generator():
...     for i in range(5):
...         await asyncio.sleep(1)
...         yield i
...

>>> async def main():
...     async for value in async_generator():
...         print(value)
...

>>> asyncio.run(main())
0
1
2
3
4

In this example, async_generator() is an asynchronous generator. It returns an iterator that yields numbers from 0 to 4, with a delay of 1 second between each number to simulate an asynchronous operation.

The main() function demonstrates how to consume the asynchronous generator using an async for loop.

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