Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add to traceback
  • Loading branch information
iritkatriel committed Dec 1, 2021
commit 8ab5e134e8313e8b401fc0d5f019df19b16ff2e8
13 changes: 13 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1224,6 +1224,19 @@ def test_syntax_error_various_offsets(self):
exp = "\n".join(expected)
self.assertEqual(exp, err)

def test_exception_with_note(self):
e = ValueError(42)
vanilla = self.get_report(e)

e.__note__ = 'My Note'
self.assertEqual(self.get_report(e), vanilla + 'My Note\n')

e.__note__ = 'Your Note'
self.assertEqual(self.get_report(e), vanilla + 'Your Note\n')

e.__note__ = None
self.assertEqual(self.get_report(e), vanilla)

def test_exception_qualname(self):
class A:
class B:
Expand Down
8 changes: 8 additions & 0 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,12 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
# Capture now to permit freeing resources: only complication is in the
# unofficial API _format_final_exc_line
self._str = _some_str(exc_value)
if exc_value is not None:
self.__note__ = exc_value.__note__
assert self.__note__ is None or isinstance(self.__note__, str)
else:
self.__note__ = None

if exc_type and issubclass(exc_type, SyntaxError):
# Handle SyntaxError's specially
self.filename = exc_value.filename
Expand Down Expand Up @@ -816,6 +822,8 @@ def format_exception_only(self):
yield _format_final_exc_line(stype, self._str)
else:
yield from self._format_syntax_error(stype)
if self.__note__ is not None:
yield self.__note__ + "\n"

def _format_syntax_error(self, stype):
"""Format SyntaxError exceptions (internal helper)."""
Expand Down
19 changes: 19 additions & 0 deletions Python/pythonrun.c
Original file line number Diff line number Diff line change
Expand Up @@ -1083,6 +1083,25 @@ print_exception(struct exception_print_context *ctx, PyObject *value)
PyErr_Clear();
}
err += PyFile_WriteString("\n", f);

if (err == 0 && PyExceptionInstance_Check(value)) {
_Py_IDENTIFIER(__note__);

PyObject *note = _PyObject_GetAttrId(value, &PyId___note__);
if (note == NULL) {
err = -1;
}
if (err == 0 && PyUnicode_Check(note)) {
err = write_indented_margin(ctx, f);
if (err == 0) {
err = PyFile_WriteObject(note, f, Py_PRINT_RAW);
}
if (err == 0) {
err = PyFile_WriteString("\n", f);
}
}
Py_XDECREF(note);
}
Py_XDECREF(tb);
Py_DECREF(value);
/* If an error happened here, don't show it.
Expand Down