aiter()

The built-in aiter() function allows you to obtain an asynchronous iterator from an asynchronous iterable. This function is supported by the .__aiter__() method. Here’s how you can use the function:

Python
>>> async def main():
...     async for item in aiter(some_async_iterable):
...         print(item)
...

>>> asyncio.run(main())

aiter() Signature

Python Syntax
aiter(async_iterable)

Arguments

Argument Description
async_iterable An object that supports asynchronous iteration.

Return Value

  • Returns an asynchronous iterator for the provided asynchronous iterable.

aiter() Examples

With an asynchronous iterable as an argument:

Python
>>> async def async_gen():
...     for i in range(3):
...         yield i
...

>>> async def main():
...     async for item in aiter(async_gen()):
...         print(item)
...

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

aiter() Common Use Cases

The most common use cases for the aiter() function include:

  • Having fine-grained control over asynchronous iteration
  • Iterating over asynchronous data sources, such as files or network streams, concurrently
  • Simplifying code that needs to handle asynchronous iteration

aiter() Real-World Example

Consider a scenario where you need to count the number of lines in multiple files concurrently. You can use the aiter() function to iterate over each file asynchronously, allowing for efficient file handling:

Python line_count.py
import asyncio
import sys
import aiofiles

async def count_lines(filename):
    num_lines = 0

    async with aiofiles.open(filename, mode="r") as file:
        lines = aiter(file)
        while True:
            try:
                await anext(lines)
                num_lines += 1
            except StopAsyncIteration:
                break

    print(f"{filename}: {num_lines}")

async def count_all_files(filenames):
    tasks = [asyncio.create_task(count_lines(file)) for file in filenames]
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(count_all_files(filenames=sys.argv[1:]))

In this example, aiter() is used to obtain an asynchronous iterator over each file, enabling concurrent processing of multiple files. This approach efficiently handles file I/O operations.

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 Nov. 22, 2024 • Reviewed by Dan Bader