Python: How to use asyncio.gather with both void and return functions

Date: 2020-04-22 | python | asyncio | gather |

problem

I'm using Python for one of my projects and wanted to add some parallelism to speed up a few async calls. I know I can use asyncio.gather to await a collection of async functions in ~parallel. Is there a way to mix functions that return a value with functions that don't in the same asyncio.gather call?

solution

You can mix functions with return values and with None returns in the same asyncio.gather call by just using placeholder variable names. Here's an example:

import asyncio

async def get_first_string_async() -> str:
    print("in first string")
    return "1"

async def get_second_string_async() -> str:
    print("in second string")
    return "2"

async def do_void_thing_async() -> None:
    print("doing void thing")
    an_operation = 1 + 1

async def main() -> None:
    first_string, second_string, __ = await asyncio.gather(
        get_first_string_async(),
        get_second_string_async(),
        do_void_thing_async()
    )

    print(first_string)
    print(second_string)
    print(__)

asyncio.run(main())

When run, this would output something like: in first string in second string doing void thing 1 2 None

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.