Skip to content

Add colorization of exceptions in default sys.unraisablehook #134170

Closed

Description

@gry321

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

Linked PRs

Activity

  1. added
    type-bug
    on May 18, 2025
  2. StanFromIreland commented on May 18, 2025

    @StanFromIreland
    Member

    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?

  3. added
    type-feature
    stdlib
    pending
    and removed
    type-bug
    on May 18, 2025
  4. picnixz commented on May 18, 2025

    @picnixz
    Member

    Yes, in this case I don't think the REPL is able to re-add colorization. It's too late IMO.

  5. ZeroIntensity commented on May 18, 2025

    @ZeroIntensity
    Member

    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:

    import traceback
    import sys
    import atexit
    
    def hook(unraisable):
        exc = unraisable.exc_value
        print(unraisable.err_msg, file=sys.stderr)
        traceback.print_exception(exc, colorize=True)
    
    sys.unraisablehook = hook
    def foo():
        raise Exception('foo')
    
    atexit.register(foo)

    Ideally, we'd just do this in C by calling into traceback._print_exception_bltin. The relevant line is here:

    if (PyTraceBack_Print(exc_tb, file) < 0) {

  6. removed
    pending
    on May 18, 2025
  7. picnixz commented on May 18, 2025

    @picnixz
    Member

    Shouldn't we chain the unraisable hooks then? what if someone already has a hook registered?

  8. ZeroIntensity commented on May 18, 2025

    @ZeroIntensity
    Member

    It wouldn't be any different than someone overwriting sys.excepthook.

  9. picnixz commented on May 18, 2025

    @picnixz
    Member

    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?)

  10. ZeroIntensity commented on May 18, 2025

    @ZeroIntensity
    Member

    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 to sys.unraisablehook.

  11. picnixz commented on May 18, 2025

    @picnixz
    Member

    My proposal is to extend that behavior to sys.unraisablehook.

    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!

  12. ZeroIntensity commented on May 18, 2025

    @ZeroIntensity
    Member

    Yeah, it's completely safe. sys.unraisablehook can already call arbitrary Python code, so we're not really adding anything new in that sense.

  13. added
    interpreter-core
    and removed
    stdlib
    on May 18, 2025
  14. changed the title [-]No colored exceptions in atexit module[/-] [+]Add colorization of exceptions in default `sys.unraisablehook`[/+] on May 18, 2025
  15. added a commit that references this issue on Aug 4, 2025
  16. ZeroIntensity commented on Aug 4, 2025

    @ZeroIntensity
    Member

    All done, thanks for the suggestions @gry321

  17. cdce8p commented on Aug 10, 2025

    @cdce8p
    Contributor

    #134183 seems to have caused a regression in a mypyc test case. AFAICT calling PyErr_WriteUnraisable now causes Exception ignore ... and the traceback to be emitted twice. The code generated by mypyc:

    static void
    F_finalize(PyObject *self)
    {
        PyObject *exc = PyErr_GetRaisedException();
        CPyDef_F_____del__(self);
        if (PyErr_Occurred() != NULL) {
            PyObject *del_str = PyUnicode_FromString("__del__");
            PyObject *del_method = (del_str == NULL) ? NULL : _PyType_Lookup(Py_TYPE(self), del_str);
            PyErr_WriteUnraisable(del_method);
            Py_XDECREF(del_method);
            Py_XDECREF(del_str);
        }
        PyErr_SetRaisedException(exc);
    }
      Exception ignored in: <slot wrapper '__del__' of 'F' objects>
      Exception ignored in: <slot wrapper '__del__' of 'F' objects>
      Traceback (most recent call last):
        File "native.py", line 5, in __del__
          raise Exception("e2")
      Exception: e2
      Traceback (most recent call last):
        File "native.py", line 5, in __del__
          raise Exception("e2")
      Exception: e2
    

    This was the mypyc test command. Note it still uses PyErr_Fetch and PyErr_Restore but the output is the same.

    pytest -n0 -s mypyc/test/test_run.py::TestRun::run-classes.test::testDelException
  18. ZeroIntensity commented on Aug 10, 2025

    @ZeroIntensity
    Member

    Hi, thanks for the heads up. I think this is a problem in mypyc.

    On a debug build, I see an assertion failure:

    python: Objects/typeobject.c:6093: _PyType_LookupStackRefAndVersion: Assertion `!PyErr_Occurred()' failed.
    

    This is because it's not always safe to call _PyType_Lookup with an exception set:

    cpython/Objects/typeobject.c

    Lines 6092 to 6093 in 046a4e3

    /* We may end up clearing live exceptions below, so make sure it's ours. */
    assert(!PyErr_Occurred());

    Anyway, if we ignore that, the underlying issue that mypyc needs to handle garbage collection during sys.unraisablehook correctly. This isn't limited to this patch; as I said, sys.unraisablehook could always call arbitrary Python code, and now we're just making it do that. mypyc needs to be able to prevent double-destruction in these cases.

    Here's a repro:

    import gc
    
    def unraisablehook(*args):
        gc.collect()
    
    sys.unraisablehook = unraisablehook
    
    class Evil:
        def __del__(self):
            raise Exception()
    
    Evil()

    If you add a print() call to __del__, you'll see that it's called twice. In C, this is how mypyc is defining the __del__:

    static void
    Evil_finalize(PyObject *self)
    {
        PyObject *type, *value, *traceback;
        PyErr_Fetch(&type, &value, &traceback);
        CPyDef_Evil_____del__(self);
        if (PyErr_Occurred() != NULL) {
            PyObject *del_str = PyUnicode_FromString("__del__");
            PyObject *del_method = (del_str == NULL) ? NULL : _PyType_Lookup(Py_TYPE(self), del_str);
            PyErr_WriteUnraisable(del_method);
            Py_XDECREF(del_method);
            Py_XDECREF(del_str);
        }
        PyErr_Restore(type, value, traceback);
    }
    
    static void
    Evil_dealloc(a___EvilObject *self)
    {
        if (!PyObject_GC_IsFinalized((PyObject *)self)) {
            Py_TYPE(self)->tp_finalize((PyObject *)self);
        }
        PyObject_GC_UnTrack(self);
        CPy_TRASHCAN_BEGIN(self, Evil_dealloc)
        Evil_clear(self);
        Py_TYPE(self)->tp_free((PyObject *)self);
        CPy_TRASHCAN_END(self)
    }

    We have some example code for tp_dealloc here. I think there are two problems at hand:

    1. The object is seemingly never untracked from the garbage collector. So, when those gc.collect() calls inside sys.unraisablehook will incorrectly think that the object needs to be destroyed. This isn't a problem after tp_free (or really, PyObject_GC_Del) because that will untrack it for you.
    2. It looks like resurrection isn't handled properly. Use PyObject_CallFinalizerFromDealloc for this. If something else resurrects it (such as the garbage collection), it needs to take responsibility for freeing the object.

    I'll submit an issue to mypyc about this.

  19. added a commit that references this issue on Aug 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions