daily notes[31]
Python内置aiter()函数用于异步编程,通过调用对象的__aiter__()方法获取异步迭代器。与同步迭代器不同,异步迭代器通过__anext__()返回可等待对象(通常为协程),需要使用await获取
·
Built-in Functions
- The Python interpreter possesses a lot of buil-in functions to help programmer achieve coding efficiently.
- calling
aiter
which means to call__aiter__()
can get an asynchronous iterator from an asynchronous iterable - for an object that implements
__aiter__
. aiter(obj)
is equivalent toobj.__aiter__()
,used in asynchronous programming (e.g., with asyncio).- Coroutine usually applies to non-blocking concurrency in a single thread for highly dense I/O operations.
- asynchronous program which has
async for
loops generally take into consideration usingaiter()
. - 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
- https://docs.python.org
- deepseek
更多推荐
所有评论(0)