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
| Parameter | Description |
|---|---|
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
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.
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
StopAsyncIterationwhen awaited. anext()returns an awaitable: don't forgetawait.
Version history
| Version | Change |
|---|---|
| Python 3.10 | Added |
Related
aiter()· Return an asynchronous iterator for an async iterable: the async counterpart of iter(), used with async for and anext().next()· Get the next item from an iterator. When it is exhausted, return the default if given, otherwise raise StopIteration.- Python Async and Await · tutorial