Skip to content

Commit 4853c83

Browse files
authored
AttributeError instances might not have a .obj (#44)
Deal with this situation without crashing. AttributeError.obj is only always there after 3.10. Fixes #43.
1 parent ac97f0f commit 4853c83

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/exceptiongroup/_formatting.py

+4
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,7 @@ def print_exc(
433433
_MAX_STRING_SIZE = 40
434434
_MOVE_COST = 2
435435
_CASE_COST = 1
436+
_SENTINEL = object()
436437

437438

438439
def _substitution_cost(ch_a, ch_b):
@@ -448,6 +449,9 @@ def _compute_suggestion_error(exc_value, tb):
448449
if wrong_name is None or not isinstance(wrong_name, str):
449450
return None
450451
if isinstance(exc_value, AttributeError):
452+
obj = getattr(exc_value, "obj", _SENTINEL)
453+
if obj is _SENTINEL:
454+
return None
451455
obj = exc_value.obj
452456
try:
453457
d = dir(obj)

tests/test_formatting.py

+24
Original file line numberDiff line numberDiff line change
@@ -504,3 +504,27 @@ def test_nameerror_suggestions_in_group(
504504
print_exception(eg)
505505
output = capsys.readouterr().err
506506
assert "Did you mean" in output and "'append'?" in output
507+
508+
509+
def test_bug_suggestions_attributeerror_no_obj(
510+
patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture
511+
) -> None:
512+
if not patched:
513+
# Block monkey patching, then force the module to be re-imported
514+
del sys.modules["traceback"]
515+
del sys.modules["exceptiongroup"]
516+
del sys.modules["exceptiongroup._formatting"]
517+
monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args))
518+
519+
from exceptiongroup import print_exception
520+
521+
class NamedAttributeError(AttributeError):
522+
def __init__(self, name: str) -> None:
523+
self.name: str = name
524+
525+
try:
526+
raise NamedAttributeError(name="mykey")
527+
except AttributeError as e:
528+
print_exception(e) # does not crash
529+
output = capsys.readouterr().err
530+
assert "NamedAttributeError" in output

0 commit comments

Comments
 (0)