Python __aiter__ Method
Last modified November 17, 2026 Python 3.15
The __aiter__ method returns an asynchronous iterator. It is the
entry point used by async for and by the built-in
aiter() function. Unlike the old generator-based protocol from
early Python 3 versions, a modern __aiter__ must return an object
with an __anext__ method directly, not a coroutine that resolves
to one. A regular def returning an iterator and an async
generator method both satisfy that rule.
How async for works
When Python executes async for value in obj, it calls
obj.__aiter__() once and keeps the returned iterator. It then
awaits iterator.__anext__() repeatedly until that call raises
StopAsyncIteration. The loop does not call __aiter__
again on each pass.
import asyncio
class AsyncCounter:
def __init__(self, stop):
self.stop = stop
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.stop:
raise StopAsyncIteration
self.current += 1
return self.current - 1
async def main():
async for value in AsyncCounter(3):
print(value)
asyncio.run(main())
AsyncCounter.__aiter__ returns self, and
__anext__ produces 0, 1, and
2 before raising StopAsyncIteration. The loop ends
normally when the exception is raised; it does not print an error. The built-in
aiter() is a shorthand for the same __aiter__
lookup.
$ python async_counter.py 0 1 2
__aiter__ must not return a coroutine
Before Python 3.7, __aiter__ was allowed to be a coroutine that
resolved to an iterator. That protocol was removed. Today an
async def __aiter__ that returns self produces a
coroutine object, and async for rejects it because a coroutine has
no __anext__ method. An async generator method, on the other hand,
is fine: because it contains yield, calling it returns an async
generator object, which is already an iterator.
import asyncio
import warnings
# Hide the unawaited-coroutine warning for this failing example.
warnings.filterwarnings("ignore", category=RuntimeWarning)
class Legacy:
async def __aiter__(self):
return self
async def __anext__(self):
raise StopAsyncIteration
async def main():
result = Legacy().__aiter__()
print(type(result).__name__)
result.close()
try:
async for _ in Legacy():
pass
except TypeError as e:
print(type(e).__name__, e)
asyncio.run(main())
The first line shows that calling the old-style method returns a coroutine.
The second line is the real error from async for: it received an
object from __aiter__ that does not implement
__anext__. The built-in aiter() also raises
TypeError for the same object, with a message that names the
method that returned the coroutine. Use a plain def __aiter__ that returns the
iterator, as in the previous example.
$ python legacy_aiter_error.py coroutine TypeError 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
Returning a separate iterator
A reusable container should return a new iterator from each
__aiter__ call. The iterator keeps its own position, so two
async for loops over the same container do not interfere. The
container only creates the iterator; it does not store the iteration state.
import asyncio
class Bag:
aiter_calls = 0
def __init__(self, items):
self.items = tuple(items)
def __aiter__(self):
Bag.aiter_calls += 1
return BagIterator(self.items)
class BagIterator:
def __init__(self, items):
self.items = items
self.index = 0
async def __anext__(self):
if self.index >= len(self.items):
raise StopAsyncIteration
value = self.items[self.index]
self.index += 1
return value
async def main():
bag = Bag(["a", "b"])
first = aiter(bag)
second = aiter(bag)
print(f"same iterator: {first is second}")
Bag.aiter_calls = 0
async for item in bag:
print(f"first loop: {item}")
async for item in bag:
print(f"second loop: {item}")
print(f"aiter calls for two loops: {Bag.aiter_calls}")
asyncio.run(main())
The two explicit aiter() calls return different objects, as shown
by same iterator: False. Each loop then asks the bag for a fresh
iterator and gets all the items again. The counter was reset before the loops,
so the final line reports exactly two calls to __aiter__, one per
loop.
$ python separate_iterator.py same iterator: False first loop: a first loop: b second loop: a second loop: b aiter calls for two loops: 2
Returning self and exhaustion
An iterator may return self from __aiter__. This is
common for streams and other single-use objects, but it also means the object
carries the iteration position. Once exhausted, a second loop finds nothing
because __anext__ keeps raising StopAsyncIteration.
import asyncio
class OneShot:
def __init__(self, items):
self.items = list(items)
self.index = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.index >= len(self.items):
raise StopAsyncIteration
value = self.items[self.index]
self.index += 1
return value
async def main():
counter = OneShot(["a", "b"])
async for item in counter:
print(f"first loop: {item}")
async for item in counter:
print(f"second loop: {item}")
print("second loop finished")
asyncio.run(main())
The first loop prints both items. The second loop makes no iterations and
immediately reaches the line after it. This is acceptable for a one-shot
source, but it is a poor design for a container that users expect to iterate
more than once. In that case, return a separate iterator object or implement
__aiter__ as an async generator method.
$ python one_shot.py first loop: a first loop: b second loop finished
Async generators implement the protocol
An async generator function already returns an object that implements
__aiter__ and __anext__. The generator object is its
own iterator, so aiter(gen) is gen is true. This is the shortest
way to create a custom asynchronous sequence when the state can be expressed
with local variables.
import asyncio
async def countdown(n):
for value in range(n, 0, -1):
await asyncio.sleep(0.01)
yield value
async def main():
gen = countdown(3)
print(type(gen).__name__)
print(f"aiter is gen: {aiter(gen) is gen}")
async for value in gen:
print(value)
asyncio.run(main())
The generator yields 3, 2, and 1, with
an await before each value. Python supplies both protocol methods
automatically and raises StopAsyncIteration when the function
returns. No explicit __aiter__ class is needed.
$ python async_generator.py async_generator aiter is gen: True 3 2 1
Checking the protocol
The collections.abc module provides
AsyncIterable and AsyncIterator for isinstance
checks. An async iterable only needs __aiter__; an async iterator
also needs __anext__. A class that returns self and
defines both methods satisfies both interfaces.
from collections.abc import AsyncIterable, AsyncIterator
class Counter:
def __init__(self, stop):
self.stop = stop
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.stop:
raise StopAsyncIteration
self.current += 1
return self.current - 1
counter = Counter(2)
print(isinstance(counter, AsyncIterable))
print(isinstance(counter, AsyncIterator))
print(aiter(counter) is counter)
All three checks are true for the counter. The distinction matters when you
write generic code: accept an AsyncIterable when you only need to
start iteration, and require an AsyncIterator when you need to
call anext() yourself. The built-in aiter() is the
standard way to obtain the iterator.
$ python protocol_check.py True True True
Best practices
Keep __aiter__ small and predictable:
- Use a regular
defthat returns an object with__anext__, or an async generator method; never return a coroutine that resolves to an iterator. - Return a new iterator from a reusable container, and return
selfonly for a deliberately single-use stream. - Keep
__aiter__free of I/O and other expensive setup. Open resources in an async context manager or lazily on the first__anext__call. - Use an async generator when the iterator can be written as a loop with
yield; use a class when you need explicit state or retry logic. - Raise
StopAsyncIterationfrom__anext__, neverStopIteration, and clean up resources if iteration is abandoned early. - Do not use
forwith an async iterator orasync forwith a synchronous one; the two protocols are separate.
Source
object.__aiter__ - Python documentation
Asynchronous iterators - Python documentation
async for - Python documentation
In this article we have implemented the __aiter__ method. We have
covered the async for protocol, the Python 3.7 change that made
__aiter__ a regular method, reusable containers versus one-shot
iterators, async generators, and the AsyncIterable and
AsyncIterator interfaces. For related topics, see
Python __anext__ method,
Python __iter__ method,
Python __next__ method,
Python aiter built-in,
Python anext built-in, and
Python async await.
Author
List all Python tutorials.