Python aiter() 函数是在 3.10 版中作为异步编程功能引入的内置函数。它返回异步可迭代对象的异步迭代器。术语 异步迭代器 定义为实现 __aiter__() 和 __anext__() 方法的对象。
在同步迭代中,程序会阻止或等待每个操作完成,然后再继续下一个操作。但是,对于本质上是异步的 aiter() 函数,允许程序启动另一个操作,而无需等待前一个操作完成。
语法
以下是 Python aiter() 函数的语法 -
aiter(asyncIterable)
参数
Python aiter() 函数接受单个参数 -
- asyncIterable − 它表示一个异步可迭代对象。
返回值
Python aiter() 函数返回一个异步迭代器。
例子
以下示例将帮助我们理解 aiter() 函数的工作原理 -
示例 1
在下面的示例中,我们将说明 Python aiter() 函数的基本用法。这里我们创建了一个异步生成器函数。它生成从 0 到 3 的数字,每个数字之间有 2 秒的延迟。
import asyncio
async def async_iter():
for num in range(4):
await asyncio.sleep(2)
yield num
async def main():
async for res in aiter(async_iter()):
print(res)
asyncio.run(main())
当我们运行上述程序时,它会产生以下结果——
0
1
2
3
1
2
3
示例 2
在下面的代码中,我们使用 aiter() 函数毫不延迟地生成一个 4 到 8 之间的数字。
import asyncio
async def async_gentr():
for num in range(4, 8):
yield num
async def main():
async for res in aiter(async_gentr()):
print(res)
asyncio.run(main())
以下是上述代码的输出 -
4
5
6
7
5
6
7
示例 3
下面的代码显示了如何将 aiter() 方法与 __aiter__() 和 __anext__() 方法结合使用。在这里,我们正在创建一个异步列表对象,然后迭代它以打印其项目。
import asyncio
class AsyncIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.index == len(self.data):
raise StopAsyncIteration
value = self.data[self.index]
self.index += 1
return value
async def main():
async_iter = AsyncIterator([18, 19, 10, 11])
async for value in aiter(async_iter):
print(value)
asyncio.run(main())
上述代码的输出如下 -
18
19
10
11
19
10
11
示例 4
在下面的代码中,我们将 aiter() 定义为一个异步生成器,它从指定的可迭代对象中生成项目。然后,它使用 sumOfnum() 方法计算它们的和,并打印结果。
import asyncio
async def aiter(iter):
for item in iter:
yield item
async def sumOfnum(iter, start=0):
async for x in aiter(iter):
start += x
return start
async def main():
numerics = [4, 12, 20, 13, 15]
total = await sumOfnum(numerics)
print(f"The sum of the numbers is {total}")
asyncio.run(main())
以下是上述代码的输出 -
The sum of the numbers is 64