How to call an async function without await?

One way would be to use create_task function:

import asyncio

async def handler_message(request):
    ...
    loop = asyncio.get_event_loop()
    loop.create_task(perform_message(x,y,z))
    ...

As per the loop documentation, starting Python 3.10, asyncio.get_event_loop() is deprecated. If you’re trying to get a loop instance from a coroutine/callback, you should use asyncio.get_running_loop() instead. This method will not work if called from the main thread, in which case a new loop must be instantiated:

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(perform_message(x, y, z))
loop.run_forever()

Furthermore, if the call is only made once throughout your program’s runtime and no other loop needs to be is instantiated (unlikely), you may use:

asyncio.run(perform_message(x, y, z))

This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario.

Leave a Comment