aiter() function in Python

aiter() function in Python

ยท

2 min read

Introduction

aiter() is a new function that came in Python 3.10 version. It returns an asynchronous iterator for an asynchronous iterable.

The syntax of the aiter() function looks like this:

aiter(iter)

where iter is an asynchronous iterable.

Examples

When you go look at this page, one of the first examples you will see looks like this the following:

result = [i async for i in aiter() if i % 2]

If you attempt to follow that syntax though, you'll end up with SyntaxError .

$ py main.py
  File "C:\Users\ashut\Desktop\Test\Blog-Codes\Built-Ins\aiter\main.py", line 1
    result = [i async for i in aiter() if i % 2]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: asynchronous comprehension outside of an asynchronous function

To create a real async comprehension, you will need to call another async def function. Let's see an example:

import asyncio

async def numbers(nums):
    for i in range(nums):
        yield i
        await asyncio.sleep(0.5)

async def main():
    odd_nums = [i async for i in aiter(numbers(10)) if i % 2 == 0]
    print(odd_nums)

if __name__ == " __main__":
    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(main())
    finally:
        event_loop.close()

When you run this code, you'll get this output:

[0, 2, 4, 6, 8]

In the above code, the numbers() function is an asynchronous generator that is yielding values to our asynchronous list comprehension.

Conclusion

This was a brief introduction to aiter() in Python. You can find more examples here.

Did you find this article valuable?

Support Ashutosh Writes by becoming a sponsor. Any amount is appreciated!

ย