Skip to content
Advertisement

How to suppress “coroutine was never awaited” warning?

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]

Advertisement

Answer

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
>>>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement