Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-99139: Improve NameError error suggestion for instances #99140

Merged
merged 7 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ Important deprecations, removals or restrictions:
Improved Error Messages
=======================

* 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. Contributed by Pablo Galindo in :gh:`99139`.

>>> class A:
... def __init__(self):
... self.blech = 1
...
... def foo(self):
... somethin = blech

>>> A().foo()
Traceback (most recent call last):
File "<stdin>", line 1
somethin = blech
^^^^^
NameError: name 'blech' is not defined. Did you mean: 'self.blech'?


* Improve the :exc:`SyntaxError` error message when the user types ``import x
from y`` instead of ``from y import x``. Contributed by Pablo Galindo in :gh:`98931`.

Expand Down
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
25 changes: 25 additions & 0 deletions Python/suggestions.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#define NEEDS_PY_IDENTIFIER

#include "Python.h"
#include "pycore_frame.h"

Expand Down Expand Up @@ -226,6 +228,25 @@ get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
return NULL;
}

// Are we inside a method and the instance has an attribute called 'name'?
_Py_IDENTIFIER(self);
PyObject* self_str = _PyUnicode_FromId(&PyId_self); /* borrowed */
if (PySequence_Contains(dir, self_str) > 0) {
PyObject* locals = PyFrame_GetLocals(frame);
if (!locals) {
goto error;
}
PyObject* self = PyDict_GetItemString(locals, "self"); /* borrowed */
Py_DECREF(locals);
if (!self) {
goto error;
}

if (PyObject_HasAttr(self, name)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not use PyObject_HasAttr. It is broken by design.

return PyUnicode_FromFormat("self.%S", name);
}
}

PyObject *suggestions = calculate_suggestions(dir, name);
Py_DECREF(dir);
if (suggestions != NULL) {
Expand All @@ -250,6 +271,10 @@ get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
Py_DECREF(dir);

return suggestions;

error:
Py_XDECREF(dir);
return NULL;
}

static bool
Expand Down