Skip to content

Commit 88f00e3

Browse files
sobolevnPranjal095
authored andcommitted
pythongh-132385: Fix instance error suggestions trigger potential exceptions in traceback (python#132387)
1 parent cfbfa50 commit 88f00e3

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
@@ -4594,6 +4594,28 @@ def foo(self):
45944594
actual = self.get_suggestion(instance.foo)
45954595
self.assertNotIn("self.blech", actual)
45964596

4597+
def test_unbound_local_error_with_side_effect(self):
4598+
# gh-132385
4599+
class A:
4600+
def __getattr__(self, key):
4601+
if key == 'foo':
4602+
raise AttributeError('foo')
4603+
if key == 'spam':
4604+
raise ValueError('spam')
4605+
4606+
def bar(self):
4607+
foo
4608+
def baz(self):
4609+
spam
4610+
4611+
suggestion = self.get_suggestion(A().bar)
4612+
self.assertNotIn('self.', suggestion)
4613+
self.assertIn("'foo'", suggestion)
4614+
4615+
suggestion = self.get_suggestion(A().baz)
4616+
self.assertNotIn('self.', suggestion)
4617+
self.assertIn("'spam'", suggestion)
4618+
45974619
def test_unbound_local_error_does_not_match(self):
45984620
def func():
45994621
something = 3

Lib/traceback.py

Lines changed: 5 additions & 1 deletion
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:
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)