在尝试聚合来自异步生成器的结果时,如下所示:
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/