Skip to content

Commit 30964d1

Browse files
[3.12] gh-113358: Fix rendering tracebacks with exceptions with a broken __getattr__ (GH-113359)
(cherry picked from commit 04fabe2) Co-authored-by: Jérome Perrin <perrinjerome@gmail.com> Co-authored-by: Irit Katriel <1055913+iritkatriel@users.noreply.github.com>
1 parent ae2a25b commit 30964d1

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

Lib/test/test_traceback.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1654,6 +1654,20 @@ def __repr__(self):
16541654
err_msg = "b'please do not show me as numbers'"
16551655
self.assertEqual(self.get_report(e), vanilla + err_msg + '\n')
16561656

1657+
# an exception with a broken __getattr__ raising a non expected error
1658+
class BrokenException(Exception):
1659+
broken = False
1660+
def __getattr__(self, name):
1661+
if self.broken:
1662+
raise ValueError(f'no {name}')
1663+
1664+
e = BrokenException(123)
1665+
vanilla = self.get_report(e)
1666+
e.broken = True
1667+
self.assertEqual(
1668+
self.get_report(e),
1669+
vanilla + "Ignored error getting __notes__: ValueError('no __notes__')\n")
1670+
16571671
def test_exception_with_multiple_notes(self):
16581672
for e in [ValueError(42), SyntaxError('bad syntax')]:
16591673
with self.subTest(e=e):

Lib/traceback.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,11 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
738738
# Capture now to permit freeing resources: only complication is in the
739739
# unofficial API _format_final_exc_line
740740
self._str = _safe_string(exc_value, 'exception')
741-
self.__notes__ = getattr(exc_value, '__notes__', None)
741+
try:
742+
self.__notes__ = getattr(exc_value, '__notes__', None)
743+
except Exception as e:
744+
self.__notes__ = [
745+
f'Ignored error getting __notes__: {_safe_string(e, '__notes__', repr)}']
742746

743747
if exc_type and issubclass(exc_type, SyntaxError):
744748
# Handle SyntaxError's specially
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix rendering tracebacks with exceptions with a broken __getattr__

0 commit comments

Comments
 (0)