Skip to content

Commit bb56dea

Browse files
authored
gh-98254: Include stdlib module names in error messages for NameErrors (#98255)
1 parent 3a639bb commit bb56dea

File tree

6 files changed

+101
-31
lines changed

6 files changed

+101
-31
lines changed

Lib/idlelib/idle_test/test_run.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ def __eq__(self, other):
3939

4040
data = (('1/0', ZeroDivisionError, "division by zero\n"),
4141
('abc', NameError, "name 'abc' is not defined. "
42-
"Did you mean: 'abs'?\n"),
42+
"Did you mean: 'abs'? "
43+
"Or did you forget to import 'abc'?\n"),
4344
('int.reel', AttributeError,
4445
"type object 'int' has no attribute 'reel'. "
4546
"Did you mean: 'real'?\n"),

Lib/test/test_traceback.py

+15
Original file line numberDiff line numberDiff line change
@@ -3185,6 +3185,21 @@ def func():
31853185
actual = self.get_suggestion(func)
31863186
self.assertNotIn("something", actual)
31873187

3188+
def test_name_error_for_stdlib_modules(self):
3189+
def func():
3190+
stream = io.StringIO()
3191+
3192+
actual = self.get_suggestion(func)
3193+
self.assertIn("forget to import 'io'", actual)
3194+
3195+
def test_name_error_for_private_stdlib_modules(self):
3196+
def func():
3197+
stream = _io.StringIO()
3198+
3199+
actual = self.get_suggestion(func)
3200+
self.assertIn("forget to import '_io'", actual)
3201+
3202+
31883203

31893204
class PurePythonSuggestionFormattingTests(
31903205
PurePythonExceptionFormattingMixin,

Lib/traceback.py

+7
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,13 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
712712
suggestion = _compute_suggestion_error(exc_value, exc_traceback)
713713
if suggestion:
714714
self._str += f". Did you mean: '{suggestion}'?"
715+
if issubclass(exc_type, NameError):
716+
wrong_name = getattr(exc_value, "name", None)
717+
if wrong_name is not None and wrong_name in sys.stdlib_module_names:
718+
if suggestion:
719+
self._str += f" Or did you forget to import '{wrong_name}'"
720+
else:
721+
self._str += f". Did you forget to import '{wrong_name}'"
715722
if lookup_lines:
716723
self._load_lines()
717724
self.__suppress_context__ = \
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Modules from the standard library are now potentially suggested as part of the
2+
error messages displayed by the interpreter when an :exc:`NameError` is raised
3+
to the top level. Patch by Pablo Galindo

Python/pythonrun.c

-7
Original file line numberDiff line numberDiff line change
@@ -1107,16 +1107,9 @@ print_exception_suggestions(struct exception_print_context *ctx,
11071107
PyObject *f = ctx->file;
11081108
PyObject *suggestions = _Py_Offer_Suggestions(value);
11091109
if (suggestions) {
1110-
// Add a trailer ". Did you mean: (...)?"
1111-
if (PyFile_WriteString(". Did you mean: '", f) < 0) {
1112-
goto error;
1113-
}
11141110
if (PyFile_WriteObject(suggestions, f, Py_PRINT_RAW) < 0) {
11151111
goto error;
11161112
}
1117-
if (PyFile_WriteString("'?", f) < 0) {
1118-
goto error;
1119-
}
11201113
Py_DECREF(suggestions);
11211114
}
11221115
else if (PyErr_Occurred()) {

Python/suggestions.c

+74-23
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include "pycore_pyerrors.h"
55
#include "pycore_code.h" // _PyCode_GetVarnames()
6+
#include "stdlib_module_names.h" // _Py_stdlib_module_names
67

78
#define MAX_CANDIDATE_ITEMS 750
89
#define MAX_STRING_SIZE 40
@@ -175,7 +176,7 @@ calculate_suggestions(PyObject *dir,
175176
}
176177

177178
static PyObject *
178-
offer_suggestions_for_attribute_error(PyAttributeErrorObject *exc)
179+
get_suggestions_for_attribute_error(PyAttributeErrorObject *exc)
179180
{
180181
PyObject *name = exc->name; // borrowed reference
181182
PyObject *obj = exc->obj; // borrowed reference
@@ -195,35 +196,25 @@ offer_suggestions_for_attribute_error(PyAttributeErrorObject *exc)
195196
return suggestions;
196197
}
197198

198-
199199
static PyObject *
200-
offer_suggestions_for_name_error(PyNameErrorObject *exc)
200+
offer_suggestions_for_attribute_error(PyAttributeErrorObject *exc)
201201
{
202-
PyObject *name = exc->name; // borrowed reference
203-
PyTracebackObject *traceback = (PyTracebackObject *) exc->traceback; // borrowed reference
204-
// Abort if we don't have a variable name or we have an invalid one
205-
// or if we don't have a traceback to work with
206-
if (name == NULL || !PyUnicode_CheckExact(name) ||
207-
traceback == NULL || !Py_IS_TYPE(traceback, &PyTraceBack_Type)
208-
) {
202+
PyObject* suggestion = get_suggestions_for_attribute_error(exc);
203+
if (suggestion == NULL) {
209204
return NULL;
210205
}
206+
// Add a trailer ". Did you mean: (...)?"
207+
PyObject* result = PyUnicode_FromFormat(". Did you mean: %R?", suggestion);
208+
Py_DECREF(suggestion);
209+
return result;
210+
}
211211

212-
// Move to the traceback of the exception
213-
while (1) {
214-
PyTracebackObject *next = traceback->tb_next;
215-
if (next == NULL || !Py_IS_TYPE(next, &PyTraceBack_Type)) {
216-
break;
217-
}
218-
else {
219-
traceback = next;
220-
}
221-
}
222-
223-
PyFrameObject *frame = traceback->tb_frame;
224-
assert(frame != NULL);
212+
static PyObject *
213+
get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
214+
{
225215
PyCodeObject *code = PyFrame_GetCode(frame);
226216
assert(code != NULL && code->co_localsplusnames != NULL);
217+
227218
PyObject *varnames = _PyCode_GetVarnames(code);
228219
if (varnames == NULL) {
229220
return NULL;
@@ -261,6 +252,66 @@ offer_suggestions_for_name_error(PyNameErrorObject *exc)
261252
return suggestions;
262253
}
263254

255+
static bool
256+
is_name_stdlib_module(PyObject* name)
257+
{
258+
const char* the_name = PyUnicode_AsUTF8(name);
259+
Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
260+
for (Py_ssize_t i = 0; i < len; i++) {
261+
if (strcmp(the_name, _Py_stdlib_module_names[i]) == 0) {
262+
return 1;
263+
}
264+
}
265+
return 0;
266+
}
267+
268+
static PyObject *
269+
offer_suggestions_for_name_error(PyNameErrorObject *exc)
270+
{
271+
PyObject *name = exc->name; // borrowed reference
272+
PyTracebackObject *traceback = (PyTracebackObject *) exc->traceback; // borrowed reference
273+
// Abort if we don't have a variable name or we have an invalid one
274+
// or if we don't have a traceback to work with
275+
if (name == NULL || !PyUnicode_CheckExact(name) ||
276+
traceback == NULL || !Py_IS_TYPE(traceback, &PyTraceBack_Type)
277+
) {
278+
return NULL;
279+
}
280+
281+
// Move to the traceback of the exception
282+
while (1) {
283+
PyTracebackObject *next = traceback->tb_next;
284+
if (next == NULL || !Py_IS_TYPE(next, &PyTraceBack_Type)) {
285+
break;
286+
}
287+
else {
288+
traceback = next;
289+
}
290+
}
291+
292+
PyFrameObject *frame = traceback->tb_frame;
293+
assert(frame != NULL);
294+
295+
PyObject* suggestion = get_suggestions_for_name_error(name, frame);
296+
bool is_stdlib_module = is_name_stdlib_module(name);
297+
298+
if (suggestion == NULL && !is_stdlib_module) {
299+
return NULL;
300+
}
301+
302+
// Add a trailer ". Did you mean: (...)?"
303+
PyObject* result = NULL;
304+
if (!is_stdlib_module) {
305+
result = PyUnicode_FromFormat(". Did you mean: %R?", suggestion);
306+
} else if (suggestion == NULL) {
307+
result = PyUnicode_FromFormat(". Did you forget to import %R?", name);
308+
} else {
309+
result = PyUnicode_FromFormat(". Did you mean: %R? Or did you forget to import %R?", suggestion, name);
310+
}
311+
Py_XDECREF(suggestion);
312+
return result;
313+
}
314+
264315
// Offer suggestions for a given exception. Returns a python string object containing the
265316
// suggestions. This function returns NULL if no suggestion was found or if an exception happened,
266317
// users must call PyErr_Occurred() to disambiguate.

0 commit comments

Comments
 (0)