Search code examples
pythonpython-asyncio

How to have conditional logic within asyncio.gather?


I want to run an async function conditionally, something like this:

one, two, three = await asyncio.gather(
    some_async_method1(),
    some_async_method2() if some_condition else None, # None doesn't work here
    some_async_method3()
)

I expect two to be None when some_condition is False. How to make this work?


Solution

  • You can create a function

    async def await_none():
        return None
    

    And then change your code to

        some_async_method2() if some_condition else await_none(),
    

    There might be a simpler way of doing this.