How to suppress "coroutine was never awaited" warning?

Viewed 1882

All search results on "coroutine was never awaited" are for people who were either trying to fire-and-forget or actually did forget to await. This is not my case.

I want to use a coroutine the same way I often use generators: I'm creating it here while I have all the variables handy, but I'm not sure yet whether I'll ever need that to be run. Something like:

options = {
   'a': async_func_1(..., ...),
   'b': async_func_2(),
   'c': async_func_3(...),
}

and elsewhere:

appropriate_option = figure_the_option_out(...)
result = await options[appropriate_option]
4 Answers

I still haven't found something that can be done at initialization, but I found a solution that can be done after all coroutines are awaited.

for coroutine in options.values():
    coroutine.close()

This close() function will work on all coroutines, whether awaited or not.

deceze's comment that you should not create the coroutine object until you are ready to await it is probably the most ideal solution.

But if that isn't practical, you can use weakref.finalize() to call the coroutine object's close() method just before it is garbage-collected.

>python -m asyncio
asyncio REPL 3.9.5 (default, May 18 2021, 14:42:02) [MSC v.1916 64 bit (AMD64)] on win32
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> import weakref
>>> async def coro(x):
...     print(x)
...
>>> coro_obj = coro('Hello')
>>> del coro_obj
<console>:1: RuntimeWarning: coroutine 'coro' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
>>> coro_obj = coro('Hello')
>>> _ = weakref.finalize(coro_obj, coro_obj.close)
>>> del coro_obj
>>>

You could suppress the warnings by using the -W flag in Python.

python -W ignore my_script.py
Related