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

2020.04.22 | 156 words |

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 - I built this! If you want more content like this subscribe to my email list, connect with me around the web, or take a look at some of my other projects.

More Projects

comments powered by Disqus