Quantcast
Channel: How can I call an async function without await? - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by 0xZ3RR0 for How can I call an async function without await?

$
0
0

Since Python 3.7 this can be easily achieved via asyncio.create_task.

import asyncio# replace with handler_message or whichever function you want to callasyncio.create_task(YOUR_ASYNC_FUNCTION(ARG1, ARG2, ETC))

Do note that that the Python docs do additionally say this:

Important

Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:background_tasks = set()

    task = asyncio.create_task(some_coro(param=i))    # Add task to the set. This creates a strong reference.    background_tasks.add(task)    # To prevent keeping references to finished tasks forever,    # make each task remove its own reference from the set after    # completion:    task.add_done_callback(background_tasks.discard) ```

Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>