From 1f40d5f8eabba7c23cf0fe1c958ddc0e6467edbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9rome=20Perrin?= Date: Thu, 21 Dec 2023 13:54:44 +0000 Subject: [PATCH] Fix rendering tracebacks with exceptions with a broken __getattr__ --- Lib/test/test_traceback.py | 12 ++++++++++++ Lib/traceback.py | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index a6708119b81191..f6480bb8d67338 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -2209,6 +2209,18 @@ def __repr__(self): err_msg = "b'please do not show me as numbers'" self.assertEqual(self.get_report(e), vanilla + err_msg + '\n') + # an exception with a broken __getattr__ raising a non expected error + class BrokenException(Exception): + broken = False + def __getattr__(self, name): + if self.broken: + raise ValueError(f'no {name}') + + e = BrokenException(123) + vanilla = self.get_report(e) + e.broken = True + self.assertEqual(self.get_report(e), vanilla) + def test_exception_with_multiple_notes(self): for e in [ValueError(42), SyntaxError('bad syntax')]: with self.subTest(e=e): diff --git a/Lib/traceback.py b/Lib/traceback.py index 1cf008c7e9da97..7ef363c31d08a1 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -1051,7 +1051,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 = _safe_string(exc_value, 'exception') - self.__notes__ = getattr(exc_value, '__notes__', None) + notes = None + try: + notes = getattr(exc_value, '__notes__', None) + except Exception: + pass + self.__notes__ = notes self._is_syntax_error = False self._have_exc_type = exc_type is not None