Python 3 reference · Built-in Functions

Python anext() Function

Await and return the next item from an asynchronous iterator, or a default value when it is exhausted.

Python 3 Since 3.10

Syntax

awaitable anext(async_iterator)
awaitable anext(async_iterator, default)

Parameters

ParameterDescription
async_iterator An asynchronous iterator, for example from aiter() or an async generator.
default optional Returned instead of raising StopAsyncIteration when there are no more items.

Return value

An awaitable; awaiting it gives the next item (or default).

Examples

Read items one at a time
import asyncio

async def numbers():
    yield 1
    yield 2

async def main():
    gen = numbers()
    print(await anext(gen))
    print(await anext(gen))
    print(await anext(gen, "done"))

asyncio.run(main())

Output

1
2
done

Run this on your computer — see “Get Started” for setup.

Read a header, then loop over the rest
import asyncio

async def rows():
    for row in ["id,name", "1,Ada", "2,Linus"]:
        yield row

async def main():
    stream = rows()
    header = await anext(stream)  # first line is the header
    print("header:", header)
    async for row in stream:
        print("row:", row)

asyncio.run(main())

Output

header: id,name
row: 1,Ada
row: 2,Linus

Run this on your computer — see “Get Started” for setup.

Good to know

  • Without a default, an exhausted iterator raises StopAsyncIteration when awaited.
  • anext() returns an awaitable: don't forget await.

Version history

VersionChange
Python 3.10Added