Python aiter() 语法
aiter() 是 Python 3.10 新增的一个内置函数,它用于获取一个 “异步可迭代对象” 对应的 “异步迭代器”。
其中,aiter 是 “async iterable” 的缩写。
语法:
aiter(async_iterable)说明:
aiter() 函数接收单个参数。
async_iterable(必选):是一个异步可迭代对象。
aiter() 函数会返回一个异步迭代器对象,支持通过 anext() 或 async for 来获取元素。此外,小伙伴们需要清楚以下 2 个核心概念。
- 异步可迭代对象 : 必须实现 __aiter__() 方法(返回异步迭代器)。
- 异步迭代器 : 必须实现 __anext__() 方法(返回 awaitable 对象)。
注意: 与 iter() 函数不同,aiter() 函数没有两个参数的语法版本。
Python aiter() 摘要
| 使用频率 | 中 |
|---|---|
| 最低版本 | Python 3.10 |
| 官方文档 | 查看 |
| 相关函数 | anext()、iter()、next() |
Python aiter() 示例
接下来,我们通过几个简单的例子来讲解一下 Python aiter() 函数是如何使用的。
注意: 绿叶网的 Python 在线编译器只会一次性返回所有结果。对于本节所有示例,必须在本地运行才会有异步效果。
示例 1:aiter() 基本用法
import asyncio
class AsyncCounter:
def __init__(self, stop):
self.current = 0
self.stop = stop
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.stop:
raise StopAsyncIteration
await asyncio.sleep(1) # 模拟异步操作
self.current += 1
return self.current - 1
async def main():
async for num in aiter(AsyncCounter(3)):
print(num)
# 输出 : 0 → 1 → 2(间隔 1 秒)
asyncio.run(main())运行结果如下。
0
1
2分析:
在上面例子中,我们首先定义了一个名为 AsyncCounter 的类。在该类中,__aiter__() 返回自身迭代器,而 __anext__() 每次生成一个数值并模拟异步延迟(每隔 1 秒)。
然后,aiter() 显式获取异步迭代器,async for 隐式调用 anext()。遍历结束后,触发 StopAsyncIteration 异常并退出循环。
示例 2:aiter() 搭配 anext() 使用
import asyncio
async def fetch_data():
# 模拟异步数据流
data = ['A', 'B', 'C']
for item in data:
await asyncio.sleep(1)
yield item
async def main():
ait = aiter(fetch_data())
print(await anext(ait)) # A
print(await anext(ait)) # B
print(await anext(ait, 'END')) # C
print(await anext(ait, 'END')) # END(触发默认值)
asyncio.run(main())运行结果如下。
A
B
C
END分析:
在上面代码中,首先定义了一个异步生成器 fetch_data(),它模拟了一个异步数据流,依次生成 ['A', 'B', 'C'],每次生成之间延迟 1 秒。
在 main() 函数中,使用 aiter() 获取异步迭代器,并通过 anext() 逐个获取数据。当数据流耗尽时,anext() 会返回默认值 'END'。最终,asyncio.run(main()) 运行异步程序,输出结果为 A、B、C 和 END。
