Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fail instead of printing "Exception ignored in: <coroutine..."

When explicitly telling Python to treat a RuntimeWarning as an exception, the Warning becomes an Exception successfully. But now I get an Exception ignored, and the program still doesn't fail where it should. Minimal reproducible example:

import asyncio
import warnings

async def main():
    asyncio.sleep(1)
    print("I don't want this printed.")

warnings.filterwarnings("error", category=RuntimeWarning)
asyncio.run(main())
Exception ignored in: <coroutine object sleep at 0x7f1e4f3d1b40>
Traceback (most recent call last):
File "/home/teresaejunior/.asdf/installs/python/3.9.2/lib/python3.9/warnings.py", line 506, in _warn_unawaited_coroutine
    warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)
RuntimeWarning: coroutine 'sleep' was never awaited
I don't want this printed.

How can I stop Python from ignoring the exception raised by the warnings module?

like image 566
Teresa e Junior Avatar asked Dec 01 '25 20:12

Teresa e Junior


1 Answers

How can I stop Python from ignoring this exception?

Sadly, I don't think you can, at least not in an obvious way. The problem is that this warning is printed while the coroutine object is being destroyed, that being the earliest point at which Python can be certain that you'll never await the coroutine.

Exceptions cannot be raised from destructors, because destructors are run during garbage collection and at other sensitive times. So when Python detects an exception at that time, it just ignores it, as the message says.

like image 133
user4815162342 Avatar answered Dec 03 '25 10:12

user4815162342