Skip to content

Commit 641253c

Browse files
authored
gh-132385: Fix instance error suggestions trigger potential exceptions in traceback (#132387)
1 parent 20f8ed5 commit 641253c

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Lib/test/test_traceback.py

+22
Original file line numberDiff line numberDiff line change
@@ -4555,6 +4555,28 @@ def foo(self):
45554555
actual = self.get_suggestion(instance.foo)
45564556
self.assertNotIn("self.blech", actual)
45574557

4558+
def test_unbound_local_error_with_side_effect(self):
4559+
# gh-132385
4560+
class A:
4561+
def __getattr__(self, key):
4562+
if key == 'foo':
4563+
raise AttributeError('foo')
4564+
if key == 'spam':
4565+
raise ValueError('spam')
4566+
4567+
def bar(self):
4568+
foo
4569+
def baz(self):
4570+
spam
4571+
4572+
suggestion = self.get_suggestion(A().bar)
4573+
self.assertNotIn('self.', suggestion)
4574+
self.assertIn("'foo'", suggestion)
4575+
4576+
suggestion = self.get_suggestion(A().baz)
4577+
self.assertNotIn('self.', suggestion)
4578+
self.assertIn("'spam'", suggestion)
4579+
45584580
def test_unbound_local_error_does_not_match(self):
45594581
def func():
45604582
something = 3

Lib/traceback.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1636,7 +1636,11 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
16361636
# has the wrong name as attribute
16371637
if 'self' in frame.f_locals:
16381638
self = frame.f_locals['self']
1639-
if hasattr(self, wrong_name):
1639+
try:
1640+
has_wrong_name = hasattr(self, wrong_name)
1641+
except Exception:
1642+
has_wrong_name = False
1643+
if has_wrong_name:
16401644
return f"self.{wrong_name}"
16411645

16421646
try:
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)