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

如何在Python的AsyncGenerator/AsyncIterator中实现__contains__检查?

异步生成器无法使用in运算符的替代方案

Python标准库目前没有提供直接支持异步生成器使用in运算符的语法,也没有内置的异步版本元素检查函数。

同步迭代器能通过in检查元素,是因为in运算符是为同步可迭代对象设计的,它会自动遍历同步迭代器直到找到目标元素或迭代结束。但异步生成器属于异步可迭代对象,必须通过async for语法来遍历,无法被同步的in运算符处理,这就是你遇到argument of type 'async_generator' is not iterable错误的原因。

你可以自己实现一个异步的包含检查函数,逻辑和同步in完全一致,同时保留异步迭代的惰性特性:

import asyncio

async def async_contains(async_gen, target):
    async for item in async_gen:
        if item == target:
            return True
    return False

async def my_iterator():
    print('A')
    yield 1
    print('B')
    yield 2
    print('C')
    yield 3 

async def main():
    result = await async_contains(my_iterator(), 2)
    print(result)
    # 输出顺序:
    # A
    # B
    # True

asyncio.run(main())

这个函数会逐个异步获取生成器的元素,一旦找到目标值就立即返回True并终止迭代,避免多余的计算;如果遍历完所有元素都没找到目标,就返回False。

内容的提问来源于stack exchange,提问作者Kyle Tennison

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:09:51