From 656ff084207dc866ff2bc8a700d90a5462569988 Mon Sep 17 00:00:00 2001 From: Shahar Naveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Tue, 28 Apr 2026 15:10:33 +0300 Subject: [PATCH] Update `traceback.py` from 3.14.4 (#7702) --- Lib/test/test_traceback.py | 21 +++++++++++++++++++++ Lib/traceback.py | 22 ++++++++++++---------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index fcaf1aa9e..7d5c45747 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -4287,6 +4287,27 @@ class SuggestionFormattingTestBase: self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, '_luch'))) self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, 'bluch'))) + def test_getattr_suggestions_with_custom___dir__(self): + class M(type): + def __dir__(cls): + return [None, "fox"] + + class C0: + def __dir__(self): + return [..., "bluch"] + + class C1(C0, metaclass=M): + pass + + self.assertNotIn("'bluch'", self.get_suggestion(C0, "blach")) + self.assertIn("'bluch'", self.get_suggestion(C0(), "blach")) + + self.assertIn("'fox'", self.get_suggestion(C1, "foo")) + self.assertNotIn("'fox'", self.get_suggestion(C1(), "foo")) + + self.assertNotIn("'bluch'", self.get_suggestion(C1, "blach")) + self.assertIn("'bluch'", self.get_suggestion(C1(), "blach")) + def test_getattr_suggestions_do_not_trigger_for_long_attributes(self): class A: blech = None diff --git a/Lib/traceback.py b/Lib/traceback.py index 5a34a2b87..79f67b987 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -1589,17 +1589,23 @@ def _substitution_cost(ch_a, ch_b): return _MOVE_COST +def _get_safe___dir__(obj): + # Use obj.__dir__() to avoid a TypeError when calling dir(obj). + # See gh-131001 and gh-139933. + try: + d = obj.__dir__() + except TypeError: # when obj is a class + d = type(obj).__dir__(obj) + return sorted(x for x in d if isinstance(x, str)) + + def _compute_suggestion_error(exc_value, tb, wrong_name): if wrong_name is None or not isinstance(wrong_name, str): return None if isinstance(exc_value, AttributeError): obj = exc_value.obj try: - try: - d = dir(obj) - except TypeError: # Attributes are unsortable, e.g. int and str - d = list(obj.__class__.__dict__.keys()) + list(obj.__dict__.keys()) - d = sorted([x for x in d if isinstance(x, str)]) + d = _get_safe___dir__(obj) hide_underscored = (wrong_name[:1] != '_') if hide_underscored and tb is not None: while tb.tb_next is not None: @@ -1614,11 +1620,7 @@ def _compute_suggestion_error(exc_value, tb, wrong_name): elif isinstance(exc_value, ImportError): try: mod = __import__(exc_value.name) - try: - d = dir(mod) - except TypeError: # Attributes are unsortable, e.g. int and str - d = list(mod.__dict__.keys()) - d = sorted([x for x in d if isinstance(x, str)]) + d = _get_safe___dir__(mod) if wrong_name[:1] != '_': d = [x for x in d if x[:1] != '_'] except Exception: