Special Method Protocols

__anext__() — async protocol

Return an awaitable yielding the next asynchronous item. Raise StopAsyncIteration at exhaustion, not StopIteration. An async def method is a convenient implementation.

Formal Syntax & Structure

python syntaxpython
async def __anext__(self):

Return Value

awaitable

Awaitable resolving to next item. The coroutine returned by this async def is awaited by the protocol.

Working Example

Example Snippetpython
import asyncioclass Stream:    def __init__(self): self.n=2    def __aiter__(self): return self    async def __anext__(self):        if not self.n: raise StopAsyncIteration        self.n-=1        return self.nasync def demo(): return [x async for x in Stream()]print(asyncio.run(demo()))
Python Reference