Skip to content

Commit 04fabe2

Browse files
gh-113358: Fix rendering tracebacks with exceptions with a broken __getattr__ (GH-113359)
Co-authored-by: Irit Katriel <[email protected]>
1 parent 17b73ab commit 04fabe2

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
@@ -2209,6 +2209,20 @@ def __repr__(self):
22092209
err_msg = "b'please do not show me as numbers'"
22102210
self.assertEqual(self.get_report(e), vanilla + err_msg + '\n')
22112211

2212+
# an exception with a broken __getattr__ raising a non expected error
2213+
class BrokenException(Exception):
2214+
broken = False
2215+
def __getattr__(self, name):
2216+
if self.broken:
2217+
raise ValueError(f'no {name}')
2218+
2219+
e = BrokenException(123)
2220+
vanilla = self.get_report(e)
2221+
e.broken = True
2222+
self.assertEqual(
2223+
self.get_report(e),
2224+
vanilla + "Ignored error getting __notes__: ValueError('no __notes__')\n")
2225+
22122226
def test_exception_with_multiple_notes(self):
22132227
for e in [ValueError(42), SyntaxError('bad syntax')]:
22142228
with self.subTest(e=e):

Lib/traceback.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1051,7 +1051,11 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
10511051
# Capture now to permit freeing resources: only complication is in the
10521052
# unofficial API _format_final_exc_line
10531053
self._str = _safe_string(exc_value, 'exception')
1054-
self.__notes__ = getattr(exc_value, '__notes__', None)
1054+
try:
1055+
self.__notes__ = getattr(exc_value, '__notes__', None)
1056+
except Exception as e:
1057+
self.__notes__ = [
1058+
f'Ignored error getting __notes__: {_safe_string(e, '__notes__', repr)}']
10551059

10561060
self._is_syntax_error = False
10571061
self._have_exc_type = exc_type is not None
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)