gh-99139: Improve NameError error suggestion for instances by pablogsal · Pull Request #99140 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Doc/whatsnew/3.12.rst
1 change: 1 addition & 0 deletions Include/internal/pycore_global_strings.h
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(seek)
STRUCT_FOR_ID(seekable)
STRUCT_FOR_ID(selectors)
STRUCT_FOR_ID(self)
STRUCT_FOR_ID(send)
STRUCT_FOR_ID(sep)
STRUCT_FOR_ID(sequence)
Expand Down
7 changes: 7 additions & 0 deletions Include/internal/pycore_runtime_init_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -3356,6 +3356,31 @@ def func():

actual = self.get_suggestion(func)
self.assertNotIn("blech", actual)

def test_name_error_with_instance(self):
class A:
def __init__(self):
self.blech = None
def foo(self):
blich = 1
x = blech

instance = A()
actual = self.get_suggestion(instance.foo)
self.assertIn("self.blech", actual)

def test_unbound_local_error_with_instance(self):
class A:
def __init__(self):
self.blech = None
def foo(self):
blich = 1
x = blech
blech = 1

instance = A()
actual = self.get_suggestion(instance.foo)
self.assertNotIn("self.blech", actual)

def test_unbound_local_error_does_not_match(self):
def func():
Expand Down
10 changes: 10 additions & 0 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,16 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
+ list(frame.f_globals)
+ list(frame.f_builtins)
)

# Check first if we are in a method and the instance
# has the wrong name as attribute
if 'self' in frame.f_locals:
self = frame.f_locals['self']
if hasattr(self, wrong_name):
return f"self.{wrong_name}"

# Compute closest match

if len(d) > _MAX_CANDIDATE_ITEMS:
return None
wrong_name_len = len(wrong_name)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Improve the error suggestion for :exc:`NameError` exceptions for instances.
Now if a :exc:`NameError` is raised in a method and the instance has an
attribute that's exactly equal to the name in the exception, the suggestion
will include ``self.<NAME>`` instead of the closest match in the method
scope. Patch by Pablo Galindo
23 changes: 23 additions & 0 deletions Python/suggestions.c