![]() |
VOOZH | about |
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:
Output:
1
2
3
Explanation:
aiter(asyncIterable)
Parameters:
Returns:
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.
Output:
News 1
News 2
News 3
Explanation:
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.
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.