Suppose we are trying to access a nonexistent attribute:
>>> {'foo': 'bar'}.gte('foo')
Pythons AttributeError has an args attribute with a string containing the final error message: 'dict' object has no attribute 'gte'
Using inspect and / or traceback with sys.last_traceback , is there a way to get a real dict object?
>>> offending_object = get_attributeerror_obj(sys.last_traceback) >>> dir(offending_object) [... 'clear', 'copy', 'fromkeys', 'get',
Edit: since the cat still got out of the bag, I shared my findings and code (please do not allow this and do not send it to PyPI, please;))
AttributeError created here , which shows that theres is not explicitly referencing the source object.
Here's a code with the same placeholder function:
import sys import re import difflib AE_MSG_RE = re.compile(r"'(\w+)' object has no attribute '(\w+)'") def get_attributeerror_obj(tb): ??? old_hook = sys.excepthook def did_you_mean_hook(type, exc, tb): old_hook(type, exc, tb) if type is AttributeError: match = AE_MSG_RE.match(exc.args[0]) sook = match.group(2) raising_obj = get_attributeerror_obj(tb) matches = difflib.get_close_matches(sook, dir(raising_obj)) if matches: print('\n\nDid you mean?', matches[0], file=sys.stderr) sys.excepthook = did_you_mean_hook
python exception
flying sheep
source share