Skip to content

StopAsyncIteration

StopAsyncIteration is a built-in exception that signals the end of an asynchronous iteration. This exception is specifically used in asynchronous iterators to indicate that there are no further items to yield. When you implement an asynchronous iterator, you raise it in the .__anext__() method to stop iteration.

You don’t typically catch this exception directly. Instead, you make sure your asynchronous iterators raise this exception to terminate iteration.

StopAsyncIteration Occurs When

  • The asynchronous iterator has no further items to yield

StopAsyncIteration Can Be Used When

  • Indicating the end of an asynchronous iteration in custom asynchronous iterators
  • Implicitly controlling the flow of asynchronous iteration in async for loops

StopAsyncIteration Examples

An example of when the exception appears:

Language: Python
>>> import asyncio

>>> async def one_item():
...     yield 0
...

>>> async def demonstrate_exception():
...     items = one_item()
...     await items.__anext__()  # Consumes the only item
...     await items.__anext__()  # Nothing left; raises
...

>>> asyncio.run(demonstrate_exception())
Traceback (most recent call last):
    ...
StopAsyncIteration

You usually don’t call .__anext__() directly in real code, and you generally won’t see StopAsyncIteration raised because Python handles it during normal control flow.

Here’s an example of when you might raise the exception in a custom asynchronous iterator:

Language: Python
>>> import asyncio

>>> class AsyncCounter:
...     def __init__(self, stop):
...         self.current = 0
...         self.stop = stop
...
...     async def __anext__(self):
...         if self.current >= self.stop:
...             raise StopAsyncIteration
...         await asyncio.sleep(0)  # Yield control to the event loop
...         self.current += 1
...         return self.current - 1
...
...     def __aiter__(self):
...         return self
...

>>> counter = AsyncCounter(5)

>>> async def main():
...     async for number in counter:
...         print(number)
...

>>> asyncio.run(main())
0
1
2
3
4

In this example, AsyncCounter is an asynchronous iterator that counts from 0 to stop. When current reaches stop, the iterator raises a StopAsyncIteration exception to end it.

Tutorial

Asynchronous Iterators and Iterables in Python

In this tutorial, you'll learn how to create and use asynchronous iterators and iterables in Python. You'll explore their syntax and structure and discover how they can be leveraged to handle asynchronous operations more efficiently.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 6, 2026 • Reviewed by Martin Breuss