VOOZH about

URL: https://www.geeksforgeeks.org/python/aiter-in-python/

⇱ aiter() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

aiter() in Python

Last Updated : 23 Jul, 2025

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:

  • 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.

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.

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 .
Comment
Article Tags: