我已经完成了关于异步列表理解的本教程。现在我想尝试异步字典理解。这是要复制的代码:
import asyncio
async def div7_tuple(x):
return x, x/7
async def main():
lost = [4, 8, 15, 16, 23, 42]
awaitables = asyncio.gather(*[div7_tuple(x) for x in lost])
print({k: v for k, v in awaitables})
if __name__ == '__main__':
asyncio.run(main())
但是,这会导致异常:
> RuntimeError: await wasn't used with future
> sys:1: RuntimeWarning:coroutine 'div7_tuple' was never awaited
如何用
asyncio.gather()
做到这一点?
奇怪的是,这对于构造未排序的对象来说不能以未排序的方式工作,因为如果我尝试以排序的方式它就可以工作:
async def div7(x):
return x/7
async def main2():
lost = [4, 8, 15, 16, 23, 42]
print({k: await v for k, v in [(x, div7(x)) for x in lost]})
gather()
给你一个 Future 对象。如果您需要对象的结果(以便迭代它),您需要首先 await
:
async def main():
lost = [4, 8, 15, 16, 23, 42]
awaitables = asyncio.gather(*[div7_tuple(x) for x in lost])
print({k: v for k, v in await awaitables})
或:
async def main():
lost = [4, 8, 15, 16, 23, 42]
awaitables = await asyncio.gather(*[div7_tuple(x) for x in lost])
print({k: v for k, v in awaitables})