Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch sys.unraisablehook to format exception groups #21

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ Version history

This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.

**UNRELEASED**

- Patch ``sys.unraisablehook`` to properly format exceptiongroups

**1.0.0rc8**

- Don't monkey patch anything if ``sys.excepthook`` has been altered
Expand Down
15 changes: 15 additions & 0 deletions src/exceptiongroup/_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,17 @@ def exceptiongroup_excepthook(
sys.stderr.write("".join(traceback.format_exception(etype, value, tb)))


def exceptiongroup_unraisablehook(__unraisable: sys.UnraisableHookArgs) -> None:
err_msg = __unraisable.err_msg or "Exception ignored in"
formatted_tb = "".join(traceback.format_tb(__unraisable.exc_traceback))
formatted_tb += "".join(
traceback.format_exception(
__unraisable.exc_type, __unraisable.exc_value, __unraisable.exc_traceback
)
)
sys.stderr.write(f"{err_msg}: {__unraisable.object!r}\n{formatted_tb}")


if sys.excepthook is sys.__excepthook__:
traceback_exception_original_init = traceback.TracebackException.__init__
traceback.TracebackException.__init__ = ( # type: ignore[assignment]
Expand All @@ -271,3 +282,7 @@ def exceptiongroup_excepthook(
traceback.TracebackException, "_format_syntax_error", None
)
sys.excepthook = exceptiongroup_excepthook

# Patch sys.unraisablehook if it's untouched
if sys.version_info >= (3, 8) and sys.unraisablehook is sys.__unraisablehook__:
sys.unraisablehook = exceptiongroup_unraisablehook
42 changes: 42 additions & 0 deletions tests/test_formatting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import gc
import sys

import pytest

from exceptiongroup import ExceptionGroup


Expand Down Expand Up @@ -119,3 +122,42 @@ def test_formatting_syntax_error(capsys):
SyntaxError: invalid syntax
"""
)


@pytest.mark.skipif(
sys.version_info < (3, 8), reason="sys.unraisablehook was added in Python 3.8"
)
@pytest.mark.skipif(
sys.version_info >= (3, 11),
reason="sys.unraisablehook is not touched on Python >= 3.11",
)
def test_unraisablehook(capsys, monkeypatch):
# Pytest overrides sys.unraisablehook, so we temporarily override that here
from exceptiongroup._formatting import exceptiongroup_unraisablehook

monkeypatch.setattr(sys, "unraisablehook", exceptiongroup_unraisablehook)

class Foo:
def __del__(self):
raise ExceptionGroup("the bad", [Exception("critical debug information")])

Foo()
gc.collect()

lineno = Foo.__del__.__code__.co_firstlineno
module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup."
output = capsys.readouterr().err
assert output == (
f"""\
Exception ignored in: {Foo.__del__!r}
File "{__file__}", line {lineno + 1}, in __del__
raise ExceptionGroup("the bad", [Exception("critical debug information")])
+ Exception Group Traceback (most recent call last):
| File "{__file__}", line {lineno + 1}, in __del__
| raise ExceptionGroup("the bad", [Exception("critical debug information")])
| {module_prefix}ExceptionGroup: the bad (1 sub-exception)
+-+---------------- 1 ----------------
| Exception: critical debug information
+------------------------------------
"""
)