简体   繁体   English

python asyncio.gather 使用输入作为返回值的一部分

[英]python asyncio.gather use input as part of return value

I have a function something like我有一个 function 之类的东西

async def funcn(input: input_type) -> output_type:
  ....
  return output

I am calling it using asyncio.gather like:我使用 asyncio.gather 来调用它,例如:

output = await asyncio.gather(*[funcn(input) for input in input_list])

Here return value will be List of output for each input in the input_list.这里的返回值将是 input_list 中每个输入的 output 列表。

But I want the return value to be something like [(input, output)] for each input in input_list.但我希望 input_list 中每个输入的返回值类似于 [(input, output)]。 Is it possible somehow without changing the implementation of the function?在不改变 function 的实现的情况下是否有可能?

The return of asyncio.gather will be returned in the same order as the input, so you just need to zip your input_list with output : asyncio.gather的返回将以与输入相同的顺序返回,因此您只需将 zip 您的input_listoutput一起返回:

for input_value, output_value in zip(input_list, output):
    print(input_value, output_value)

In addition to zip from deceze's answer, you could always wrap funcn with another function that returns the input and the output.除了zip的回答中的 zip 之外,您始终可以使用另一个返回输入的 function 和 output 来包装funcn That allows you to decorate the output without modifying the processing function:这允许您在不修改处理 function 的情况下装饰 output:

async def wrap_funcn(input):
    output = await funcn(input)
    return input, output

...
ins_and_outs = await asyncio.gather(*[wrap_funcn(input) for input in input_list])

This can be useful in case input_list is an iterator whose contents is spent after the call to gather() which exhausts it.这在input_list是一个迭代器的情况下很有用,它的内容是在调用gather()之后耗尽它的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM