在 python 3.10 中,我们看到了新的内置函数 aiter(async_iterable)。在 python 文档中。定义是“为异步迭代返回异步迭代器”。但我无法理解如何在 google/youtube 中使用或不使用示例定义。有谁知道如何使用这个内置功能?
问问题
190 次
1 回答
1
aiter()
并anext()
调用对象的__aiter__()
and __anext__()
,如果存在的话。它们本质上是和的异步等价iter()
物next()
。在大多数情况下,您只想简单地使用async for
, 来代替。但是,要了解什么aiter()
和anext()
正在做什么,协程using_async_for()
和using_aiter_anext()
以下示例中的协程大致等效:
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())
于 2021-12-24T06:27:03.517 回答