假设我们尝试访问一个不存在的属性:
>>> {'foo': 'bar'}.gte('foo') # well, I meant “get”!
Python仅具有包含已完成错误消息的字符串AttributeError
的属性:args
'dict' object has no attribute 'gte'
使用inspect
和/或traceback
模块sys.last_traceback
,有没有办法掌握实际的 dict 对象?
>>> offending_object = get_attributeerror_obj(sys.last_traceback)
>>> dir(offending_object)
[...
'clear',
'copy',
'fromkeys',
'get', # ah, here it is!
'items',
...]
编辑:因为无论如何猫已经不在了,我会分享我的发现和代码(请不要解决这个问题并提交给 PyPI,拜托;))
AttributeError
是在此处创建的,这表明显然没有对附加的原始对象的引用。
这里的代码具有相同的占位符功能:
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