You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用aiter()与anext()内置函数操作异步迭代器

异步迭代内置函数aiter/anext使用方法

aiter()和anext()是Python 3.10新增的异步场景内置函数,对应同步逻辑下的iter()和next(),使用逻辑和同步版本高度一致,仅因为异步特性需要配合await使用:

  • aiter(异步可迭代对象):调用对象的__aiter__方法,返回异步迭代器实例
  • anext(异步迭代器 [, 默认值]):调用迭代器的__anext__方法,返回可等待对象,需要用await接收返回值;迭代结束时如果没传默认值会抛出StopAsyncIteration异常,传了默认值则直接返回默认值。

结合你的代码场景的实现示例

你提供的自定义AIter类、异步生成器get_range都属于合法的异步可迭代对象,都可以直接用这两个函数实现迭代,替代async for语法糖的写法如下:

import asyncio

async def get_range():
    for i in range(10):
        print(f"start {i}")
        await asyncio.sleep(1)
        print(f"end {i}")
        yield i

class AIter:
    def __init__(self, N):
        self.i = 0
        self.N = N

    def __aiter__(self):
        return self

    async def __anext__(self):
        i = self.i
        print(f"start {i}")
        await asyncio.sleep(1)
        print(f"end {i}")
        if i >= self.N:
            raise StopAsyncIteration
        self.i += 1
        return i

async def main():
    # 示例1:迭代自定义AIter类
    # 第一步:用aiter获取异步迭代器
    async_iter = aiter(AIter(10))
    while True:
        try:
            # 第二步:用anext+await取值
            p = await anext(async_iter)
            print(f"finally {p}")
        except StopAsyncIteration:
            # 捕获迭代终止异常退出循环
            break

    # 示例2:迭代异步生成器get_range,逻辑完全一致
    # async_gen_iter = aiter(get_range())
    # while True:
    #     try:
    #         p = await anext(async_gen_iter)
    #         print(f"finally {p}")
    #     except StopAsyncIteration:
    #         break

if __name__ == "__main__":
    asyncio.run(main())

anext带默认值的用法

如果不需要捕获迭代终止异常,可以给anext传第二个参数作为默认值,迭代结束时直接返回默认值不会抛出异常:

async def main():
    async_iter = aiter(AIter(3))
    print(await anext(async_iter)) # 输出 0
    print(await anext(async_iter)) # 输出 1
    print(await anext(async_iter)) # 输出 2
    print(await anext(async_iter, -1)) # 迭代结束,返回默认值-1,无异常

内容的提问来源于stack exchange,提问作者Ahmad Ismail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:54:00