Python 3 reference · Built-in Functions
Python aiter() Function
Return an asynchronous iterator for an async iterable: the async counterpart of iter(), used with async for and anext().
Python 3 Since 3.10
Syntax
aiter(async_iterable)
Parameters
| Parameter | Description |
|---|---|
async_iterable |
An object with an __aiter__() method, such as an async generator. |
Return value
An asynchronous iterator (the result of calling __aiter__()).
Examples
import asyncio
async def countdown(n):
while n > 0:
yield n
n -= 1
async def main():
it = aiter(countdown(3))
print(await anext(it))
print(await anext(it))
asyncio.run(main())
Output
3 2
Run this on your computer — see “Get Started” for setup.
import asyncio
async def letters():
for ch in "abc":
await asyncio.sleep(0)
yield ch
async def main():
async for ch in aiter(letters()):
print(ch)
asyncio.run(main())
Output
a b c
Run this on your computer — see “Get Started” for setup.
Good to know
async forcallsaiter()for you; call it yourself only when you need the iterator object, for example to read the first item withanext()before looping over the rest.- It only works on async iterables. For normal lists and generators use
iter().
Version history
| Version | Change |
|---|---|
| Python 3.10 | Added |
Related
anext()· Await and return the next item from an asynchronous iterator, or a default value when it is exhausted.iter()· Get an iterator from an iterable, or create one that calls a function until it returns a sentinel value.next()· Get the next item from an iterator. When it is exhausted, return the default if given, otherwise raise StopIteration.- Python Async and Await · tutorial