agronholm / exceptiongroup

Backport of PEP 654 (exception groups)
Other
42 stars 20 forks source link

Patch `traceback.TracebackException.format_exception_only()` #7

Closed Zac-HD closed 2 years ago

Zac-HD commented 2 years ago

It turns out that this is used by pytest, and so we'll need to add something along the lines of

import collections, traceback

def _safe_string(value, what, func=str):
    try:
        return func(value)
    except:
        return f"<{what} {func.__name__}() failed>"

def format_exception_only_with_note(self):
    yield from format_exception_only_base(self)
    if isinstance(self.__notes__, collections.abc.Sequence):
        for note in self.__notes__:
            note = _safe_string(note, "note")
            yield from [l + "\n" for l in note.split("\n")]
    elif self.__notes__ is not None:
        yield _safe_string(self.__notes__, "__notes__", func=repr)

format_exception_only_base = traceback.TracebackException.format_exception_only
traceback.TracebackException.format_exception_only = format_exception_only_with_note

(quick dump from local debugging; I'll arrange a better PR in the next few days)