Skip to content

Commit 16e9e74

Browse files
[3.13] gh-132385: Fix instance error suggestions trigger potential exceptions in traceback (GH-132387) (#133297)
gh-132385: Fix instance error suggestions trigger potential exceptions in `traceback` (GH-132387) (cherry picked from commit 641253c) Co-authored-by: sobolevn <[email protected]>
1 parent 6a919d0 commit 16e9e74

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Lib/test/test_traceback.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4549,6 +4549,28 @@ def foo(self):
45494549
actual = self.get_suggestion(instance.foo)
45504550
self.assertNotIn("self.blech", actual)
45514551

4552+
def test_unbound_local_error_with_side_effect(self):
4553+
# gh-132385
4554+
class A:
4555+
def __getattr__(self, key):
4556+
if key == 'foo':
4557+
raise AttributeError('foo')
4558+
if key == 'spam':
4559+
raise ValueError('spam')
4560+
4561+
def bar(self):
4562+
foo
4563+
def baz(self):
4564+
spam
4565+
4566+
suggestion = self.get_suggestion(A().bar)
4567+
self.assertNotIn('self.', suggestion)
4568+
self.assertIn("'foo'", suggestion)
4569+
4570+
suggestion = self.get_suggestion(A().baz)
4571+
self.assertNotIn('self.', suggestion)
4572+
self.assertIn("'spam'", suggestion)
4573+
45524574
def test_unbound_local_error_does_not_match(self):
45534575
def func():
45544576
something = 3

Lib/traceback.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1528,7 +1528,11 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
15281528
# has the wrong name as attribute
15291529
if 'self' in frame.f_locals:
15301530
self = frame.f_locals['self']
1531-
if hasattr(self, wrong_name):
1531+
try:
1532+
has_wrong_name = hasattr(self, wrong_name)
1533+
except Exception:
1534+
has_wrong_name = False
1535+
if has_wrong_name:
15321536
return f"self.{wrong_name}"
15331537

15341538
try:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix instance error suggestions trigger potential exceptions
2+
in :meth:`object.__getattr__` in :mod:`traceback`.

0 commit comments

Comments
 (0)