ZetCode

Python __anext__ Method

Last modified November 17, 2026 Python 3.15

The __anext__ method produces the next value of an asynchronous iterator. It is the asynchronous counterpart of __next__ and is called by async for and by the built-in anext() function. This article shows how to implement it, how to signal the end of iteration, and how to handle awaits and errors inside the method.

Calling __anext__ directly

__anext__ must return an awaitable that resolves to the next value. Defining it with async def is the usual approach; a regular method that returns an awaitable also works. The built-in anext(iterator) awaits the method for you, and anext(iterator, default) returns the default when StopAsyncIteration is raised.

manual_anext.py
import asyncio


class AsyncCounter:
    def __init__(self, stop):
        self.stop = stop
        self.current = 0

    def __aiter__(self):
        return self

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


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

    print(await anext(counter))
    print(await anext(counter))
    print(await anext(counter, "exhausted"))

    try:
        await anext(counter)
    except StopAsyncIteration:
        print("StopAsyncIteration raised")


asyncio.run(main())

The first two calls return 0 and 1. The third call uses the default and prints exhausted instead of raising. The final call has no default, so StopAsyncIteration propagates and is caught by the try block. After an iterator is exhausted, every further call should keep raising StopAsyncIteration.

$ python manual_anext.py
0
1
exhausted
StopAsyncIteration raised

Awaiting inside __anext__

Because __anext__ is a coroutine, it can await other operations while producing a value. This is what makes asynchronous iteration useful for I/O: the producer can wait for the next value without blocking the event loop, so other tasks can run during the wait.

async_for.py
import asyncio


class AsyncCounter:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.stop:
            raise StopAsyncIteration
        await asyncio.sleep(0.05)
        self.current += 1
        return self.current - 1


async def main():
    async for number in AsyncCounter(3):
        print(number)


asyncio.run(main())

Each pass through the loop awaits __anext__, which sleeps for a short time before returning the next number. The values are produced sequentially, so the total delay is the sum of the individual delays. For concurrent work, create several tasks rather than relying on a single iterator.

$ python async_for.py
0
1
2

The StopIteration trap

A coroutine must not let StopIteration escape. Python's PEP 479 converts it into RuntimeError, because a stray StopIteration would otherwise be confused with the normal completion of a generator. This matters when __anext__ wraps a synchronous iterator and calls next().

stopiteration_bug.py
import asyncio


class SyncWrapper:
    def __init__(self, values):
        self.values = iter(values)

    def __aiter__(self):
        return self

    async def __anext__(self):
        return next(self.values)


async def main():
    try:
        async for value in SyncWrapper([1, 2]):
            print(value)
    except RuntimeError as e:
        print(type(e).__name__, e)


asyncio.run(main())

The first two calls return the values from the list. On the third call, next() raises StopIteration, the coroutine lets it escape, and Python turns it into RuntimeError: coroutine raised StopIteration. The async for loop never sees the normal end of iteration.

$ python stopiteration_bug.py
1
2
RuntimeError coroutine raised StopIteration

Converting to StopAsyncIteration

The fix is to catch StopIteration and raise StopAsyncIteration instead. Using from None hides the original exception from the traceback, since the end of iteration is not an error. The same conversion is needed whenever a synchronous source is adapted to asynchronous iteration.

stopiteration_fix.py
import asyncio


class SyncWrapper:
    def __init__(self, values):
        self.values = iter(values)

    def __aiter__(self):
        return self

    async def __anext__(self):
        try:
            return next(self.values)
        except StopIteration:
            raise StopAsyncIteration from None


async def main():
    async for value in SyncWrapper([1, 2]):
        print(value)

    print("iteration finished")


asyncio.run(main())

Now the loop prints both values and finishes normally. The raise ... from None form is optional, but it keeps the traceback clean if the exception is inspected. Do not catch and ignore StopIteration inside a loop that still has more work to do; only the end of the underlying iterator should produce StopAsyncIteration.

$ python stopiteration_fix.py
1
2
iteration finished

Retrying inside __anext__

A custom iterator can retry a transient failure before giving up. The retry logic belongs inside __anext__, because the consumer sees only values and the final exception. The following reader fails twice on its second item, then succeeds on the third attempt.

retry_anext.py
import asyncio


class FlakyReader:
    def __init__(self, values):
        self.values = list(values)
        self.index = 0
        self.failures = {1: 2}

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.index >= len(self.values):
            raise StopAsyncIteration

        for attempt in range(1, 4):
            try:
                value = self._read()
            except ConnectionError as e:
                if attempt == 3:
                    raise
                print(f"attempt {attempt} failed for {self.values[self.index]!r}: {e}")
                await asyncio.sleep(0.01)
            else:
                self.index += 1
                return value

    def _read(self):
        if self.failures.get(self.index, 0) > 0:
            self.failures[self.index] -= 1
            raise ConnectionError("temporary read error")
        return self.values[self.index]


async def main():
    async for value in FlakyReader(["a", "b", "c"]):
        print(f"got {value!r}")


asyncio.run(main())

The first item is returned immediately. For the second item, the method catches ConnectionError, waits briefly, and tries again. The method allows three attempts and reraises if all of them fail; in this run the third attempt succeeds. The consumer receives 'a', 'b', and 'c' in order; the intermediate failures are handled inside the iterator and do not become exceptions in the loop.

$ python retry_anext.py
got 'a'
attempt 1 failed for 'b': temporary read error
attempt 2 failed for 'b': temporary read error
got 'b'
got 'c'

Async generators provide __anext__

Most asynchronous iterators are easier to write as async generators. The generator function contains yield, and Python supplies __aiter__ and __anext__ automatically. The built-in anext() still works, and so does async for.

async_generator.py
import asyncio
import inspect


async def counter(stop):
    for value in range(stop):
        await asyncio.sleep(0.01)
        yield value


async def main():
    gen = counter(3)
    print(inspect.isasyncgen(gen))
    print(await anext(gen))
    print(await anext(gen))

    async for value in gen:
        print(value)


asyncio.run(main())

inspect.isasyncgen confirms the type. The two manual anext() calls consume the first two values, and the remaining async for loop receives the last one. This mixed style is useful for testing or for skipping a header item before handing the generator to a loop.

$ python async_generator.py
True
0
1
2

Best practices

An asynchronous iterator should be predictable and should release resources when iteration ends:

Source

object.__anext__ - Python documentation

Asynchronous iterators - Python documentation

async for - Python documentation

anext - Python documentation

In this article we have implemented the __anext__ method. We have covered manual anext() calls, awaiting inside the method, the StopIteration to StopAsyncIteration conversion, retries, and async generators. For related topics, see Python __aiter__ method, Python __next__ method, Python anext built-in, Python aiter built-in, Python iterators, and Python async await.

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.