Python Reference ยท Built-in Functions
Python aiter() and anext() functions
Reference for Python aiter() and anext() (3.10+): get an async iterator, fetch its next item with await, supply a default, and loop with async for.
aiter() and anext() are the asynchronous counterparts of iter() and next(). They were added in Python 3.10. aiter(x) returns an asynchronous iterator for an asynchronous iterable by calling its __aiter__() method. anext(it) returns an awaitable that produces the next item, or raises StopAsyncIteration when the iterator is finished.
Most code never calls them directly because async for does the same job. They are useful when you want to pull one item manually, peek at the first value of an async generator, or give a default instead of an exception.
it = aiter(source) first = await anext(it)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
In a script, you start the coroutine with asyncio.run(main()). The runner above supports top-level await main() instead.
Syntax
aiter(async_iterable) anext(async_iterator) anext(async_iterator, default)
| Name | Description |
|---|---|
async_iterable |
An object with __aiter__(), such as an async generator. |
async_iterator |
An object with __anext__(). |
default |
Optional. Returned (as the result of the await) when the iterator is exhausted. |
Return value: aiter() returns an async iterator. anext() returns an awaitable; awaiting it gives the next item or default.
Raises: TypeError if the argument is not an async iterable or async iterator; StopAsyncIteration from the awaited anext() when finished and no default is given.
Usage notes
anext()must be awaited. Forgettingawaitgives a coroutine-like object and a "never awaited" warning instead of a value.- Only inside
async def(or a context such as the async REPL or this runner's top-levelawait). async foris simpler for walking everything; it callsaiter()once andanext()repeatedly for you.- Default value. Like
next(it, default),anext(it, default)avoids handlingStopAsyncIteration. - Async generators (an
async defwithyield) are the easiest way to create async iterators; they also haveasend(),athrow()andaclose(). - Sync iterables do not qualify. Lists and ordinary generators have no
__aiter__(); wrap them in an async generator. - Cleanup. Close partially consumed async generators with
await gen.aclose()orcontextlib.aclosing(). - Comprehensions.
[x async for x in source]collects everything; inside it the same protocol runs.
Related
iter(),next(),enumerate(),zip()- Lessons: Asyncio, Generators, Iterators