]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-132385: Fix instance error suggestions trigger potential exceptions in `traceback...
authorsobolevn <mail@sobolevn.me>
Fri, 2 May 2025 12:52:59 +0000 (15:52 +0300)
committerGitHub <noreply@github.com>
Fri, 2 May 2025 12:52:59 +0000 (15:52 +0300)
Lib/test/test_traceback.py
Lib/traceback.py
Misc/NEWS.d/next/Library/2025-04-11-12-41-47.gh-issue-132385.86HoA7.rst [new file with mode: 0644]

index a806dbf158226888a0520f546d190521b86ccb7a..683486e9aca7b278c15cd2a1f3f0355608518d6b 100644 (file)
@@ -4555,6 +4555,28 @@ class SuggestionFormattingTestBase:
         actual = self.get_suggestion(instance.foo)
         self.assertNotIn("self.blech", actual)
 
+    def test_unbound_local_error_with_side_effect(self):
+        # gh-132385
+        class A:
+            def __getattr__(self, key):
+                if key == 'foo':
+                    raise AttributeError('foo')
+                if key == 'spam':
+                    raise ValueError('spam')
+
+            def bar(self):
+                foo
+            def baz(self):
+                spam
+
+        suggestion = self.get_suggestion(A().bar)
+        self.assertNotIn('self.', suggestion)
+        self.assertIn("'foo'", suggestion)
+
+        suggestion = self.get_suggestion(A().baz)
+        self.assertNotIn('self.', suggestion)
+        self.assertIn("'spam'", suggestion)
+
     def test_unbound_local_error_does_not_match(self):
         def func():
             something = 3
index 4b3d2b636fc6b53dcaa9d8c07adfbcc5c8ce4099..16ba7fc2ee86fbddf4d53f7fbcac95aecadadb13 100644 (file)
@@ -1636,7 +1636,11 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
         # has the wrong name as attribute
         if 'self' in frame.f_locals:
             self = frame.f_locals['self']
-            if hasattr(self, wrong_name):
+            try:
+                has_wrong_name = hasattr(self, wrong_name)
+            except Exception:
+                has_wrong_name = False
+            if has_wrong_name:
                 return f"self.{wrong_name}"
 
     try:
diff --git a/Misc/NEWS.d/next/Library/2025-04-11-12-41-47.gh-issue-132385.86HoA7.rst b/Misc/NEWS.d/next/Library/2025-04-11-12-41-47.gh-issue-132385.86HoA7.rst
new file mode 100644 (file)
index 0000000..9aa2da4
--- /dev/null
@@ -0,0 +1,2 @@
+Fix instance error suggestions trigger potential exceptions
+in :meth:`object.__getattr__` in :mod:`traceback`.