asynchronous generator

In Python, an asynchronous generator is a function defined with the async def and yield statements that returns an asynchronous generator iterator. This iterator produces values asynchronously.

Asynchronous generators are particularly useful in scenarios where you need to handle asynchronous data streams efficiently.

Example

Here’s an example of an asynchronous generator function:

Python
>>> import asyncio

>>> async def async_generator():
...     for i in range(5):
...         await asyncio.sleep(1)  # Simulate an async tasks
...         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 asynchronous generator iterator that yields numbers from 0 to 4 with a delay of one second between each. The async for loop in main() consumes the values the iterator produces.

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 7, 2025 • Reviewed by Leodanis Pozo Ramos