Skip to main content

Command Palette

Search for a command to run...

aiter() function in Python

Published
2 min read
aiter() function in Python
A

Hello! I am Ashutosh and I enjoy creating things that live on the internet. I was first introduced to programming in my freshman year and since then, I started developing Web projects.

I am currently working at Thoughtworks India as an Application Developer.

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.

More from this blog

Ashutosh Writes

104 posts

Ashutosh enjoys creating things that live on the internet. He is passionate about full-stack development and DevOps. In his free time, he enjoys sharing his technical knowledge through articles.