python-3.x - 如何在 map 函数中使用 await

标签 python-3.x python-asyncio

我有以下代码

async def foo():
   some_tuple = tuple(map(bar, some_tuple))
async def bar(data):
   # Await another function and do some other stuff
   return something

因为 bar 是异步的,所以必须等待它。但是,我不确定在哪里等待 bar。我尝试在 map 中等待它,我尝试等待 map,我尝试等待 tuple,但没有任何效果。

如何在 map 中等待 bar

最佳答案

您不能将 map 与异步函数一起使用,因为 map 是同步的并且不会在循环内暂停执行。这同样适用于需要同步生成器的 tuple 构造函数。

Ti 解决这个问题,您可以用列表理解替换 map/tuple 对,它可以是异步的,并且很容易转换为元组:

some_tuple = tuple([await fn(elem) for elem in iterable])

另一种选择是使用 asyncstdlib 中的 maptuple 的异步版本包,它还提供了许多额外的有用功能:

import asyncstdlib.builtins.map as amap
import asyncstdlib.builtins.tuple as atuple

some_tuple = await atuple(amap(fn, iterable))

关于python-3.x - 如何在 map 函数中使用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62846735/

相关文章:

python - 如何在异步 Python 函数中指定返回类型?

python - 在 aiohttp 中使用共享 TCPConnector 时出错

python - 为什么我不能在异步函数中使用 'yield from'?

python - 绘制图形并退出,但保持图形窗口打开

python - 截至当前季度的 Pandas Dataframe 前向填充

regex - 删除第一行或/(正则表达式)之后的内容

python - 如何从 itertuples 中删除 "Pandas"对象名称?

python - 使用arrow python将人性化时间转换为UTC时间

python - 如何使用 Python asyncio 限制并发?

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