python - 将异步生成器聚合到元组

标签 python python-asyncio

在尝试聚合来自异步生成器的结果时,如下所示:

async def result_tuple():
    async def result_generator():
        # some await things happening in here
        yield 1
        yield 2
    return tuple(num async for num in result_generator())

我得到一个

TypeError: 'async_generator' object is not iterable

当执行 async for 行时。

但是PEP 530似乎表明它应该是有效的:

Asynchronous Comprehensions

We propose to allow using async for inside list, set and dict comprehensions. Pending PEP 525 approval, we can also allow creation of asynchronous generator expressions.

Examples:

  • set comprehension: {i async for i in agen()};
  • list comprehension: [i async for i in agen()];
  • dict comprehension: {i: i ** 2 async for i in agen()};
  • generator expression: (i ** 2 async for i in agen()).

这是怎么回事,我如何将一个异步生成器聚合到一个元组中?

最佳答案

在 PEP 摘录中,理解式并列在同一个项目符号列表中,但生成器表达式与其他表达式有很大不同。

不存在“tuple comprehension”这样的东西。 tuple() 的参数构成一个异步生成器:

tuple(num async for num in result_generator())

该行等同于 tuple(result_generator())。然后元组尝试同步迭代生成器并引发 TypeError

不过,正如问题所预期的那样,其他推导式将起作用。因此可以通过首先聚合到列表来生成元组,如下所示:

async def result_tuple():
    async def result_generator():
        # some await things happening in here
        yield 1
        yield 2
    return tuple([num async for num in result_generator()])

关于python - 将异步生成器聚合到元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52285419/

相关文章:

python - Python asyncio Streams 是否维护多个写入器和读取器的顺序?

带有异步上下文管理器的 Python 抽象方法

python - 插入在带有 Python 的 Sqlite 中不起作用

python - 如何在不阻塞父进程的情况下在python子进程中运行?

python - 数据转换为数据结构

python-3.x - 异步流检查读取器是否有数据

python - 添加不同大小的 pandas DataFrame 的值

python - 如何维护多个远程脚本执行的单个 ssh 连接?

python - asyncio后台线程: run function in main thread blocking

python - 为什么 __init__() 缺少参数?