Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

anext()

Returns an awaitable for the next item of an asynchronous iterator.

Version: Python 3.14; repository image, production runtime not attested

Syntax

await anext(async_iterator[, default])

Returns an awaitable for the next item of an asynchronous iterator.

A supplied default handles exhaustion. Without a default exhaustion raises StopAsyncIteration.

anext calls __anext__ and returns an awaitable. Awaiting the first call gets the yielded 8. On the exhausted generator, the optional default supplies the text end. Omitting the default propagates StopAsyncIteration. A yielded None counts as a real item.

import asyncio
async def gen():
    yield None
async def check():
    g = gen()
    assert await anext(g, 9) is None
    assert await anext(g, 9) == 9
asyncio.run(check())

Examples

import asyncio

async def stream():
    yield 8

async def main():
    items = stream()
    print(await anext(items))
    print(await anext(items, "end"))

asyncio.run(main())

Result

8
end

anext calls `__anext__` and returns an awaitable. Awaiting the first call gets the yielded 8. On the exhausted generator, the optional default supplies the text end. Omitting the default propagates StopAsyncIteration. A yielded None counts as a real item.

Sources