ZetCode

Python aiter function

last modified November 29, 2026 Python 3.15

In this article we show how to use the aiter builtin function, which returns an asynchronous iterator for an asynchronous iterable.

The function was added in Python 3.10 together with anext. It is the asynchronous counterpart of iter: aiter(obj) calls obj.__aiter__() and returns the result, which must be an object with an __anext__ method.

The protocol itself is described in Python __aiter__ method and Python __anext__ method. Pulling single items is covered in Python anext function, ordinary iteration in Python iterator, and asynchronous functions in Python async/await.

Getting an async iterator

An async generator is the shortest way to produce an asynchronous iterable.

first_aiter.py
import asyncio


async def numbers():
    yield 10
    yield 20
    yield 30


async def main():
    agen = numbers()
    it = aiter(agen)

    print(type(agen).__name__)
    print(it is agen)
    print(await anext(it), await anext(it), await anext(it))


asyncio.run(main())

An async generator object is already an asynchronous iterator: its __aiter__ method returns the object itself. aiter therefore returns the same object and does not copy or restart it.

The three awaited calls take the values 10, 20, and 30 in order.

$ python first_aiter.py
async_generator
True
10 20 30

What async for does

An async for loop is defined in terms of aiter and anext. The next example runs the same kind of generator twice, once with the loop and once with the functions.

async_for.py
import asyncio


async def numbers():
    for n in (1, 2, 3):
        yield n


async def main():
    async for n in numbers():
        print('async for:', n)

    it = aiter(numbers())
    while True:
        try:
            print('anext:', await anext(it))
        except StopAsyncIteration:
            break


asyncio.run(main())

The loop calls aiter once, before the first pass, and then awaits the iterator's __anext__ method until it raises StopAsyncIteration. The manual version makes the hidden steps visible.

Each call to numbers() creates a fresh generator, which is why the second part starts from one again.

$ python async_for.py
async for: 1
async for: 2
async for: 3
anext: 1
anext: 2
anext: 3

Async iterable versus async iterator

An async iterable produces an iterator; an async iterator produces values. Keeping them in separate classes allows repeated independent iteration.

protocols.py
import asyncio


class Readings:
    def __init__(self, values):
        self.values = values

    def __aiter__(self):
        return ReadingsIterator(self.values)


class ReadingsIterator:
    def __init__(self, values):
        self.values = values
        self.index = 0

    async def __anext__(self):
        if self.index >= len(self.values):
            raise StopAsyncIteration
        value = self.values[self.index]
        self.index += 1
        return value


async def main():
    readings = Readings([21.5, 22.0, 21.8])

    first = aiter(readings)
    second = aiter(readings)

    print(first is second)
    print(await anext(first), await anext(second))
    print(await anext(first))


asyncio.run(main())

Each call to __aiter__ builds a new ReadingsIterator with its own position, so the two iterators advance independently. The first iterator gives 21.5 in the second line and 22.0 in the third, while the second iterator is still at its own first value.

$ python protocols.py
False
21.5 21.5
22.0

Objects without __aiter__

An object whose class defines only __anext__ can be advanced with anext, but aiter rejects it because it is not an async iterable.

no_aiter.py
import asyncio


class Counter:
    def __init__(self, stop):
        self.stop = stop
        self.value = 0

    async def __anext__(self):
        if self.value >= self.stop:
            raise StopAsyncIteration
        self.value += 1
        return self.value


async def main():
    counter = Counter(2)

    try:
        aiter(counter)
    except TypeError as e:
        print('TypeError:', e)

    print(await anext(counter), await anext(counter))


asyncio.run(main())

The error message says that the object is not an async iterable, even though it has an __anext__ method. Adding an __aiter__ method that returns self would make it acceptable to both aiter and async for.

This is the same split as in synchronous Python, where an iterator also needs __iter__ to be usable in a for loop.

$ python no_aiter.py
TypeError: 'Counter' object is not an async iterable
1 2

Reusing and exhausting an iterator

Because an async generator is its own iterator, passing it to aiter again does not rewind it.

exhaustion.py
import asyncio


async def countdown(start):
    while start > 0:
        yield start
        start -= 1


async def main():
    it = aiter(countdown(3))
    print(await anext(it), await anext(it))

    same = aiter(it)
    print(same is it)
    print(await anext(same))
    print(await anext(same, 'done'))
    print(await anext(same, 'done'))


asyncio.run(main())

The first two values are consumed before the second aiter call, so only one value remains. After that the generator is exhausted and the default given to anext is returned on every later call.

$ python exhaustion.py
3 2
True
1
done
done

Ordinary iterables are rejected

aiter does not wrap a synchronous iterable. A list, a string, and a class that defines only __iter__ all raise TypeError.

sync_objects.py
import asyncio


class SyncOnly:
    def __iter__(self):
        return iter([1, 2, 3])


async def main():
    for value in ([1, 2, 3], 'abc', SyncOnly()):
        try:
            aiter(value)
        except TypeError as e:
            print('TypeError:', e)


asyncio.run(main())

The message names the type and says that it is not an async iterable. There is no automatic conversion, because synchronous iteration would block the event loop.

When the values are already in memory, an async generator that yields them is the usual bridge.

$ python sync_objects.py
TypeError: 'list' object is not an async iterable
TypeError: 'str' object is not an async iterable
TypeError: 'SyncOnly' object is not an async iterable

Pulling values with a timeout

A common reason to use aiter directly is to control when each value is requested. The next program reads a sensor stream inside an asyncio.timeout block.

timeout_pull.py
import asyncio


async def sensor():
    for value in (18.2, 18.4, 18.1):
        await asyncio.sleep(0.01)
        yield value


async def main():
    it = aiter(sensor())

    async with asyncio.timeout(1):
        for _ in range(3):
            print(await anext(it))

    print('next:', await anext(it, 'no more readings'))


asyncio.run(main())

The timeout applies to the whole block, so a slow producer would cancel the awaits inside it. The explicit aiter call makes the iterator a value that can be stored, passed to another function, or read with a default.

The last call does not raise, because a default was supplied.

$ python timeout_pull.py
18.2
18.4
18.1
next: no more readings

Source

Python aiter() documentation

Python asynchronous iterators

PEP 525 - asynchronous generators

In this article we have used aiter to obtain asynchronous iterators from async generators and from classes, and we have seen how async for relies on it. Continue with Python anext function for reading single items, and with Python asyncio for the surrounding machinery.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.