Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use the aiter() Built-in Function in Python?

Tags:

python-3.10

In Python 3.10 we see a newly-built-in function aiter(async_iterable).

In the Python docs, the definition is to "Return an asynchronous iterator for an asynchronous iterable", but I can't understand how to use or not use this definition with an example from Google or YouTube. Does anyone know how to use this built-in function?

like image 522
Tejas Mankar Avatar asked Nov 15 '25 10:11

Tejas Mankar


1 Answers

aiter() and anext() call an object's __aiter__() and __anext__(), if present. They're essentially the async equivalent of iter() and next(). In most cases, you'll want to simply use an async for, instead. However, to understand what aiter() and anext() are doing, the coroutines using_async_for() and using_aiter_anext() in the following example are roughly equivalent:

from asyncio import sleep, run

class Foo:
    def __aiter__(self):
        self.i = 0
        return self
    async def __anext__(self):
        await sleep(1)
        self.i += 1
        return self.i

async def using_async_for():
    async for bar in Foo():
        print(bar)
        if bar >= 10:
            break

async def using_aiter_anext():
    ai = aiter(Foo())
    try:
        while True:
            bar = await anext(ai)
            print(bar)
            if bar >= 10:
                break
    except StopAsyncIteration:
        return

async def main():
    print("Using async for:")
    await using_async_for()

    print("Using aiter/anext")
    await using_aiter_anext()

if __name__ == '__main__':
    run(main())
like image 96
GreenSmurf Avatar answered Nov 18 '25 21:11

GreenSmurf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!