Sar*_*ter 6 python-3.x python-asyncio
我有以下代码
async def foo():
some_tuple = tuple(map(bar, some_tuple))
Run Code Online (Sandbox Code Playgroud)
async def bar(data):
# Await another function and do some other stuff
return something
Run Code Online (Sandbox Code Playgroud)
由于bar是异步的,因此必须等待。然而,我不确定在哪里等待bar。我试着在里面等待map,我试着等待map,我试着等待tuple,但没有任何效果。
我如何bar在里面等待map?
您不能map与异步函数一起使用,因为映射是同步的并且不会暂停循环内的执行。这同样适用于tuple需要同步生成器的构造函数。
为了解决这个问题,您可以用列表理解替换map/tuple对,列表理解可以是异步的,并且可以轻松转换为元组:
some_tuple = tuple([await fn(elem) for elem in iterable])
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用 asyncstdlib 包的异步版本,map它还提供了许多附加且有用的功能:tuple
import asyncstdlib.builtins.map as amap
import asyncstdlib.builtins.tuple as atuple
some_tuple = await atuple(amap(fn, iterable))
Run Code Online (Sandbox Code Playgroud)