gh-98254: Include stdlib module names in error messages for NameErrors by pablogsal · Pull Request #98255 · 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
3 changes: 2 additions & 1 deletion Lib/idlelib/idle_test/test_run.py
15 changes: 15 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -3185,6 +3185,21 @@ def func():
actual = self.get_suggestion(func)
self.assertNotIn("something", actual)

def test_name_error_for_stdlib_modules(self):
def func():
stream = io.StringIO()

actual = self.get_suggestion(func)
self.assertIn("forget to import 'io'", actual)

def test_name_error_for_private_stdlib_modules(self):
def func():
stream = _io.StringIO()

actual = self.get_suggestion(func)
self.assertIn("forget to import '_io'", actual)



class PurePythonSuggestionFormattingTests(
PurePythonExceptionFormattingMixin,
Expand Down
7 changes: 7 additions & 0 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,13 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
suggestion = _compute_suggestion_error(exc_value, exc_traceback)
if suggestion:
self._str += f". Did you mean: '{suggestion}'?"
if issubclass(exc_type, NameError):
wrong_name = getattr(exc_value, "name", None)
if wrong_name is not None and wrong_name in sys.stdlib_module_names:
if suggestion:
self._str += f" Or did you forget to import '{wrong_name}'"
else:
self._str += f". Did you forget to import '{wrong_name}'"
if lookup_lines:
self._load_lines()
self.__suppress_context__ = \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Modules from the standard library are now potentially suggested as part of the
error messages displayed by the interpreter when an :exc:`NameError` is raised
to the top level. Patch by Pablo Galindo
7 changes: 0 additions & 7 deletions Python/pythonrun.c
Original file line number Diff line number Diff line change
Expand Up @@ -1107,16 +1107,9 @@ print_exception_suggestions(struct exception_print_context *ctx,
PyObject *f = ctx->file;
PyObject *suggestions = _Py_Offer_Suggestions(value);
if (suggestions) {
// Add a trailer ". Did you mean: (...)?"
if (PyFile_WriteString(". Did you mean: '", f) < 0) {
goto error;
}
if (PyFile_WriteObject(suggestions, f, Py_PRINT_RAW) < 0) {
goto error;
}
if (PyFile_WriteString("'?", f) < 0) {
goto error;
}
Py_DECREF(suggestions);
}
else if (PyErr_Occurred()) {
Expand Down
97 changes: 74 additions & 23 deletions Python/suggestions.c