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

Published: 2020-04-22 09:42:41 -0400 -0400

Reading time: 1 mins (156 words)

Tags: 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

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus