【问题标题】:TypeError: 'async_generator' object is not iterableTypeError:“async_generator”对象不可迭代
【发布时间】:2022-07-26 00:16:31
【问题描述】:

我有以下代码。

import asyncio

async def gen_random_numbers():
    for i in range(1, 3):
        await asyncio.sleep(2)
        yield [i for i in range(1, 11)]


async def random_processor():
    async for i, numbers in enumerate(gen_random_numbers()):
        print(f"working with the batch {i}  and processing {numbers}")


asyncio.run(random_processor())

但这会引发错误

async for i, numbers in enumerate(gen_random_numbers()):
TypeError: 'async_generator' object is not iterable

解决此问题的一种方法是删除枚举并保留另一个变量来跟踪它 并使用它。

有没有办法单独使用枚举来处理这个问题?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

使用asyncstdlib

import asyncstdlib

async for i, numbers in asyncstdlib.enumerate(gen_random_numbers()):
    print(f"working with the batch {i}  and processing {numbers}")

应该可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 2017-08-27
    • 2018-10-10
    • 2021-12-13
    • 2019-02-20
    • 2020-03-27
    • 2018-12-12
    • 2018-07-16
    相关资源
    最近更新 更多