Open
Description
Bug report
Bug description:
There are no colored exceptions in atexit module. Like this:
import atexit
def foo():
raise Exception('foo')
atexit.register(foo)
Exception ignored in atexit callback <function foo at 0x00000114C7D5C720>:
Traceback (most recent call last):
File "...", line 3, in foo
raise Exception('foo')
Exception: foo
Python 3.13.3
Windows 10
CPython versions tested on:
3.13
Operating systems tested on:
Windows
Activity
StanFromIreland commentedon May 18, 2025
This is because the "Exception [was] ignored in atexit callback," meaning it only appears after you exit the repl, which therefore means it is not colored. I do not find this too surprising.
cc @ambv should this be closed?
picnixz commentedon May 18, 2025
Yes, in this case I don't think the REPL is able to re-add colorization. It's too late IMO.
ZeroIntensity commentedon May 18, 2025
We could totally add colorization here! Unraisable exceptions simply invoke
sys.unraisablehook
, which we can just modify to print the exception with color.Here's a super rough POC:
Ideally, we'd just do this in C by calling into
traceback._print_exception_bltin
. The relevant line is here:cpython/Python/errors.c
Line 1489 in 0a160bf
picnixz commentedon May 18, 2025
Shouldn't we chain the unraisable hooks then? what if someone already has a hook registered?
ZeroIntensity commentedon May 18, 2025
It wouldn't be any different than someone overwriting
sys.excepthook
.picnixz commentedon May 18, 2025
Hum, maybe I misunderstood, but do you suggest we always colorize exceptions? wouldn't it be problematic to rely on colorization which is implemented in a Python file and could fail at exit? (namely, what happens if an error occurs during the colorization?)
ZeroIntensity commentedon May 18, 2025
We do always colorize exceptions in 3.13+, and fall back to the C implementation of
traceback
when it's not available. My proposal is to extend that behavior tosys.unraisablehook
.picnixz commentedon May 18, 2025
Is it safe to do it inside? namely is it safe to use this complex logic inside unraisablehook or not? if it's the case, I'm fine with this!
ZeroIntensity commentedon May 18, 2025
Yeah, it's completely safe.
sys.unraisablehook
can already call arbitrary Python code, so we're not really adding anything new in that sense.4 remaining items