Skip to content

Commit 76d2ada

Browse files
committed
pythongh-98254: Include stdlib module names in error messages for NameErrors
1 parent b863b9c commit 76d2ada

File tree

4 files changed

+87
-30
lines changed

4 files changed

+87
-30
lines changed

Lib/test/test_traceback.py

+7
Original file line numberDiff line numberDiff line change
@@ -3184,6 +3184,13 @@ def func():
31843184

31853185
actual = self.get_suggestion(func)
31863186
self.assertNotIn("something", actual)
3187+
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)
31873194

31883195

31893196
class PurePythonSuggestionFormattingTests(

Lib/traceback.py

+8
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,14 @@ 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+
mod_names = frozenset(mod for mod in sys.stdlib_module_names if not mod.startswith("_"))
717+
wrong_name = getattr(exc_value, "name", None)
718+
if wrong_name is not None and wrong_name in mod_names:
719+
if suggestion:
720+
self._str += f" Or did you forget to import '{wrong_name}'"
721+
else:
722+
self._str += f". Did you forget to import '{wrong_name}'"
715723
if lookup_lines:
716724
self._load_lines()
717725
self.__suppress_context__ = \

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

+72-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,23 @@ 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+
return PyUnicode_FromFormat(". Did you mean %R?", suggestion);
208+
}
211209

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);
210+
static PyObject *
211+
get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
212+
{
225213
PyCodeObject *code = PyFrame_GetCode(frame);
226214
assert(code != NULL && code->co_localsplusnames != NULL);
215+
227216
PyObject *varnames = _PyCode_GetVarnames(code);
228217
if (varnames == NULL) {
229218
return NULL;
@@ -261,6 +250,66 @@ offer_suggestions_for_name_error(PyNameErrorObject *exc)
261250
return suggestions;
262251
}
263252

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

0 commit comments

Comments
 (0)