anext()
anext(async_iterator, /)
anext(async_iterator, default, /) anext() awaits the next value from an async iterator. It’s the async counterpart to next(), and was added in Python 3.10 alongside aiter().
Signature
anext(async_iterator, /)
anext(async_iterator, default, /)
Both arguments are positional-only. The optional default argument is returned if the iterator is exhausted, instead of raising StopAsyncIteration.
Basic Usage
anext() returns an awaitable. Await it to get the next item:
import asyncio
async def async_range(n):
for i in range(n):
yield i
async def main():
it = async_range(3).__aiter__()
print(await anext(it)) # 0
print(await anext(it)) # 1
print(await anext(it)) # 2
print(await anext(it)) # StopAsyncIteration
asyncio.run(main())
You can also use aiter() to get the iterator first:
async def main():
it = aiter(async_range(3))
print(await anext(it)) # 0
print(await anext(it)) # 1
asyncio.run(main())
Using a Default Value
The second argument acts as a sentinel — if the iterator is exhausted, default is returned instead of raising an exception:
async def main():
it = aiter(async_range(2))
print(await anext(it, "done")) # 0
print(await anext(it, "done")) # 1
print(await anext(it, "done")) # "done" — no exception raised
asyncio.run(main())
This is cleaner than wrapping in try/except when you just want a fallback value.
Error Handling
Without a default, StopAsyncIteration is raised when the iterator is exhausted:
async def main():
it = aiter(async_range(1))
print(await anext(it)) # 0
try:
await anext(it)
except StopAsyncIteration:
print("Exhausted")
asyncio.run(main())
Note: StopAsyncIteration is the async equivalent of StopIteration. You cannot catch StopAsyncIteration with except StopIteration.
anext() vs next()
next() | anext() | |
|---|---|---|
| Accepts callable/sentinel form? | Yes — next(it, default) | No — anext(it, default) only |
| Returns awaitable? | No | Yes — must await |
| Exception on exhaust | StopIteration | StopAsyncIteration |
| Available since | Always | Python 3.10 |
See Also
- aiter() — returns an async iterator from an async iterable
- iter() — the synchronous counterpart to
aiter() - async-await-patterns — patterns for using async functions effectively