Built-in Functions

  1. The Python interpreter possesses a lot of buil-in functions to help programmer achieve coding efficiently.
  2. calling aiter which means to call __aiter__() can get an asynchronous iterator from an asynchronous iterable
  3. for an object that implements __aiter__.
  4. aiter(obj) is equivalent to obj.__aiter__(),used in asynchronous programming (e.g., with asyncio).
  5. Coroutine usually applies to non-blocking concurrency in a single thread for highly dense I/O operations.
  6. asynchronous program which has async for loops generally take into consideration using aiter().
  7. the following example illustrate how to handle aiter.
import asyncio
class AsyncCounter:
    def __init__(self, stop):
        self.stop = stop
        self.current = 0

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.stop:
            raise StopAsyncIteration
        await asyncio.sleep(1)  # Simulate async operation
        self.current += 1
        return self.current

async def main():
    async for num in AsyncCounter(100):  # Implicitly calls `aiter()`
        print(num)

asyncio.run(main())

we can apply __anext__() to return a awaitable object which is commonly coroutine. every time ,need await to acquire data.
async for loops can be explain as follows.

async_iter = aiter(async_iterable)  # 调用 __aiter__()
while True:
    try:
        x = await anext(async_iter)  # 调用 __anext__() 并 await
        print(x)
    except StopAsyncIteration:
        break

Each time we call __next__() immediately return data, be called blocking operation.Synchronous iterator usually be used to do blocking operation showed as follows.

class SyncCounter:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        self.current += 1
        return self.current

# 同步遍历
for num in SyncCounter(3):
    print(num)  # 1, 2, 3

references

  1. https://docs.python.org
  2. deepseek
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐