Python Glossary Русский

Python 3.10+Built-in functionsfunction

anext()

Built-in functions

Async analog of next(): return an awaitable for the next item of an async iterator.

Syntax

anext(async_iterator[, default])

Added in Python 3.10. It returns an awaitable, not the item: forget the await and you get a coroutine object plus a 'coroutine was never awaited' warning, while nothing is actually consumed. The second argument behaves like the one in next() — it yields a default instead of raising StopAsyncIteration, which is tidier than wrapping the call in try/except.

Examples

import asyncio
async def main():
    async def agen():
        yield 10
    it = aiter(agen())
    print(await anext(it))          # → 10
    print(await anext(it, 'конец'))  # → конец
asyncio.run(main())

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy