简体   繁体   中英

python asyncio.gather use input as part of return value

I have a function something like

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

I am calling it using asyncio.gather like:

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.

But I want the return value to be something like [(input, output)] for each input in input_list. Is it possible somehow without changing the implementation of the 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 :

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. That allows you to decorate the output without modifying the processing function:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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