Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-143811: Add helpful default error messages to AttributeError and NameError #143813

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

Open
johnslavik wants to merge 3 commits into python:main
base: main
Choose a base branch
Loading
from johnslavik:add-default-messages-attributeerror-nameerror
Open
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

Some comments aren't visible on the classic Files Changed page.

37 changes: 37 additions & 0 deletions Lib/test/test_exceptions.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2003,6 +2003,25 @@ class TestClass:

self.assertRaises(NameError, f)

def test_gh_143811(self):
def f():
span = 42
try:
spam
except NameError as exc:
# Clear the message.
exc.args = ()
raise

try:
f()
except NameError:
with support.captured_stderr() as err:
sys.__excepthook__(*sys.exc_info())

# 'spam' should appear even when message was empty.
self.assertIn("name 'spam' is not defined", err.getvalue())

# Note: name suggestion tests live in `test_traceback`.


Expand Down Expand Up @@ -2046,6 +2065,24 @@ def blech(self):
self.assertEqual("bluch", exc.name)
self.assertEqual(obj, exc.obj)

def test_gh_143811(self):
def f():
class A:
def __getattr__(self, attr):
# Provide no message.
raise AttributeError

A().bluch

try:
f()
except AttributeError:
with support.captured_stderr() as err:
sys.__excepthook__(*sys.exc_info())

# Should appear even when no message was provided.
self.assertIn("'A' object has no attribute 'bluch'", err.getvalue())

# Note: name suggestion tests live in `test_traceback`.


Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_traceback.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4259,6 +4259,7 @@ def __getattr__(self, attr):
raise AttributeError()

actual = self.get_suggestion(A(), 'bluch')
self.assertIn("'A' object has no attribute 'bluch'.", actual)
self.assertIn("blech", actual)

class A:
Expand All @@ -4267,6 +4268,7 @@ def __getattr__(self, attr):
raise AttributeError

actual = self.get_suggestion(A(), 'bluch')
self.assertIn("'A' object has no attribute 'bluch'.", actual)
self.assertIn("blech", actual)

def test_suggestions_invalid_args(self):
Expand Down Expand Up @@ -4930,6 +4932,18 @@ def func():
actual = self.get_suggestion(func)
self.assertIn("forget to import '_io'", actual)

def test_name_error_empty(self):
"""See GH-143811."""
def func():
span = 42
try:
spam
except NameError as exc:
exc.args = ()
raise
actual = self.get_suggestion(func)
self.assertIn("name 'spam' is not defined", actual)
self.assertIn("Did you mean: 'span'?", actual)


class PurePythonSuggestionFormattingTests(
Expand Down
10 changes: 8 additions & 2 deletions Lib/traceback.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1125,9 +1125,15 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
+ "add the site-packages directory to sys.path "
+ "or to enable your virtual environment?")
elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
getattr(exc_value, "name", None) is not None:
wrong_name = getattr(exc_value, "name", None)
(wrong_name := getattr(exc_value, "name", None)) is not None:
suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
if not self._str:
if issubclass(exc_type, AttributeError):
if (obj_type := type(getattr(exc_value, "obj", None))) is not type(None):
obj_type_name = object.__getattribute__(obj_type, "__name__")
self._str = f"{obj_type_name!r} object has no attribute {wrong_name!r}"
else: # NameError
self._str = f"name {wrong_name!r} is not defined"
if suggestion:
self._str += f". Did you mean: '{suggestion}'?"
if issubclass(exc_type, NameError):
Expand Down
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:exc:`AttributeError` and :exc:`NameError` exceptions raised with no message
now get helpful default messages when displaying traceback. Patch by Bartosz
Sławecki.
Loading

AltStyle によって変換されたページ (->オリジナル) /