aiter() is a built-in function that returns an asynchronous iterator object from an asynchronous iterable. This allows us to iterate over asynchronous sequences, making it ideal for non-blocking operations in asynchronous programs. It is commonly used with async for loops to iterate over data that is fetched or processed asynchronously.
Note: aiter()
was introduced in Python 3.10. Ensure that we are using Python 3.10 or later for compatibility.
Example:
Python
import asyncio
async def async_numbers():
for i in range(1, 4):
await asyncio.sleep(1) # Simulate an async task
yield i
async def main():
async for number in aiter(async_numbers()):
print(number)
asyncio.run(main())
Output:
1
2
3
Explanation:
- async_numbers() iterates over the range 1 to 3, yielding values 1, 2, and 3 sequentially, with execution paused at each yield until the next value is requested.
- main() uses an async for loop to asynchronously iterate over the async_numbers() generator, consuming and printing each yielded value without blocking the event loop.
aiter() Syntax
aiter(asyncIterable)
Parameters:
- asyncIterable represents an asynchronous iterable object.
Returns:
- aiter() returns an asynchronous iterator.
aiter() Examples
Example 1 : Reading data from an async api stream
In this example, the asynchronous generator news_feed simulates receiving news articles from an API with a delay. By using aiter() along with async for, we asynchronously consume the yielded values and print them one by one.
Python
import asyncio
# asynchronous generator function
async def news_feed():
for i in range(1, 4):
await asyncio.sleep(1) # Simulate API delay
yield f"News {i}"
# main function
async def main():
async for news in aiter(news_feed()):
print(news)
asyncio.run(main()) # calling main function
Output:
News 1
News 2
News 3
Explanation:
- news_feed() simulates an API delay with await asyncio.sleep(1) before yielding news items ("News 1", "News 2", "News 3") in a loop, allowing non-blocking execution.
- main() uses an async for loop to asynchronously iterate over the news_feed() generator, automatically awaiting each yield and printing the news items without blocking the event loop .
Example 2: Processing messages from a websocket
In this example, the asynchronous generator websocket_mock simulates a WebSocket connection by yielding messages with a delay, mimicking the process of receiving real-time messages from a server.
Python
import asyncio
# asynchronous generator function
async def websocket_mock():
messages = ["Hi!", "How are you?", "Bye!"]
for msg in messages:
await asyncio.sleep(1)
yield msg
# main function
async def main():
async for message in aiter(websocket_mock()):
print(f"Message: {message}")
asyncio.run(main()) # calling main function
Output:
Message: Hi!
Message: How are you?
Message: Bye!
Explanation:
websocket_mock()
simulates receiving messages from a WebSocket by yielding messages from a list with a 1-second delay between each, using await asyncio.sleep(1)
to mimic real-time streaming.- main() asynchronously iterates over the websocket_mock() generator using an async for loop, printing each yielded message to the console .