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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With