ZetCode

Python anext function

last modified November 29, 2026 Python 3.15

In this article we show how to use the anext builtin function, which returns the next item from an asynchronous iterator.

The call must be awaited: await anext(it). With a second argument the function returns that default instead of raising StopAsyncIteration when the iterator is exhausted. Both behaviours were added in Python 3.10.

An async iterator is obtained with Python aiter function. The synchronous version of the call is Python next function, the protocol is described in Python __anext__ method, and async generators in Python generators.

Reading items one by one

An async generator yields values that can be pulled one at a time.

first_anext.py
import asyncio


async def steps():
    yield 'start'
    yield 'middle'
    yield 'end'


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

    print(await anext(it))
    print(await anext(it))
    print(await anext(it))


asyncio.run(main())

Each call takes one value and advances the iterator. anext(it) is equivalent to await it.__anext__(), but reads better and works the same way.

The iterator comes from aiter; the same object could be used in an async for loop instead.

$ python first_anext.py
start
middle
end

The end of the iterator

When there is nothing left, the iterator signals the end with an exception.

exhausted.py
import asyncio


async def only_one():
    yield 1


async def main():
    it = aiter(only_one())
    print(await anext(it))

    try:
        await anext(it)
    except StopAsyncIteration:
        print('StopAsyncIteration')


asyncio.run(main())

An exhausted asynchronous iterator raises StopAsyncIteration, not the synchronous StopIteration. The exception is how async for knows when to stop, and it is not an error.

$ python exhausted.py
1
StopAsyncIteration

Default value

The second argument removes the need for a try block when the end of the stream is expected.

default.py
import asyncio


async def header():
    yield '# daily report'
    yield 'date: 2026-11-29'


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

    print(await anext(it))
    print(await anext(it))
    print(await anext(it, 'end of header'))
    print(await anext(it, None))


asyncio.run(main())

The third call finds the iterator exhausted and returns the string instead of raising. The fourth call returns None, which shows that the default can be any object, including one that is itself a value in the stream.

The default is a value, not a factory, so the same object comes back on every call after exhaustion.

$ python default.py
# daily report
date: 2026-11-29
end of header
None

anext needs an async iterator

An async iterable is not automatically an async iterator. The function checks for __anext__, and a container that only produces iterators fails that check.

iterator_type.py
import asyncio


class Countdown:
    def __init__(self, start):
        self.start = start

    def __aiter__(self):
        return CountdownIterator(self.start)


class CountdownIterator:
    def __init__(self, start):
        self.value = start

    async def __anext__(self):
        if self.value <= 0:
            raise StopAsyncIteration
        self.value -= 1
        return self.value + 1


async def main():
    countdown = Countdown(3)

    try:
        await anext(countdown)
    except TypeError as e:
        print('TypeError:', e)

    print(await anext(aiter(countdown)))


asyncio.run(main())

The container is an async iterable, not an async iterator: it has __aiter__ but no __anext__. aiter returns an object that has both, and that object can be passed to anext.

This is the mirror image of the example in Python aiter function where an object had __anext__ but no __aiter__.

$ python iterator_type.py
TypeError: 'Countdown' object is not an async iterator
3

Consuming with a sentinel

A default is useful in a loop, but only when the default cannot be confused with real data. A unique object makes a safe end marker.

sentinel_loop.py
import asyncio

MISSING = object()


async def tags():
    yield 'falcon'
    yield 'eagle'
    yield ''


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

    while (tag := await anext(it, MISSING)) is not MISSING:
        if tag:
            print(tag)


asyncio.run(main())

The loop stops when the default sentinel comes back. A plain empty string would not work as the end marker, because it is a legitimate value that the stream can contain; the if tag test skips it.

One shared object() is enough, since nothing else can be equal to it.

$ python sentinel_loop.py
falcon
eagle

Errors from inside the iterator

Exceptions raised by the producer are passed on unchanged. The next example shows what happens to the iterator afterwards.

errors.py
import asyncio


async def sensor():
    yield 21.5
    raise ValueError('sensor disconnected')


async def main():
    it = aiter(sensor())
    print(await anext(it))

    try:
        await anext(it)
    except ValueError as e:
        print('ValueError:', e)

    try:
        await anext(it)
    except StopAsyncIteration:
        print('the iterator is closed')


asyncio.run(main())

The exception from the generator body is not wrapped, so the caller can handle it. After the exception the async generator is finished, so the next call raises StopAsyncIteration; with a default it would return the default instead.

$ python errors.py
21.5
ValueError: sensor disconnected
the iterator is closed

Reading a header, then the rest

A frequent pattern takes the first item separately and leaves the rest to a loop.

header.py
import asyncio


async def csv_lines():
    yield 'city,population'
    yield 'Bratislava,440000'
    yield 'Košice,230000'
    yield 'Prešov,82000'


async def main():
    it = aiter(csv_lines())
    header = await anext(it)
    print(header.split(','))

    async for line in it:
        city, population = line.split(',')
        print(f'{city:12} {int(population):>8,}')


asyncio.run(main())

The first item is taken manually, and the loop continues with the same iterator. async for calls aiter on it and gets the object back, so no data is skipped or repeated.

This pattern is common for files and API responses that start with a header line.

$ python header.py
['city', 'population']
Bratislava    440,000
Košice        230,000
Prešov         82,000

Source

Python anext() documentation

Python asynchronous iterators

PEP 525 - asynchronous generators

In this article we have used anext to read single values, to detect the end of an async iterator, and to supply defaults. The iterable side is covered in Python aiter function, and the synchronous counterpart in Python next function.

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.