StopAsyncIteration
PythonINFOCommonRuntime ErrorHIGH confidence
Async iterator exhausted
Production Risk
Not a real error in async for loops; only visible when manually calling __anext__().
What this means
Raised by __anext__() to signal that an async iterator has no more items. The async for loop catches this automatically; you only see it if calling __anext__() directly.
Why it happens
- 1Calling __anext__() on an exhausted async iterator directly (outside async for)
- 2Custom async generator raises StopAsyncIteration prematurely
How to reproduce
Calling __anext__() directly on an exhausted async iterator.
trigger — this will error
trigger — this will error
import asyncio
async def main():
async def agen():
yield 1
gen = agen()
await gen.__anext__() # Gets 1
await gen.__anext__() # Raises StopAsyncIteration
asyncio.run(main())expected output
StopAsyncIteration
Fix
Use async for instead of __anext__() directly
WHEN Iterating over async generators
Use async for instead of __anext__() directly
async def main():
async for item in my_async_generator():
process(item)
# StopAsyncIteration is caught automaticallyWhy this works
async for handles StopAsyncIteration internally; only call __anext__() directly if you need manual control.
Code examples
Triggerpython
import asyncio
async def main():
async def agen():
yield 1
g = agen()
await g.__anext__()
await g.__anext__() # StopAsyncIteration
asyncio.run(main())Handle with try/exceptpython
try:
val = await gen.__anext__()
except StopAsyncIteration:
val = None # exhaustedAvoid with async forpython
async for item in my_async_gen():
process(item)
# StopAsyncIteration handled automaticallySame error in other languages
Sources
Official documentation ↗
Python Docs — Built-in Exceptions
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev