[英]Python: how to print detailed error messages about errors?
我想获得有关每个变量处理错误的详细信息。
例1:
user = User()
print(user.name)
...
AttributeError: variable 'user' (class User) doesn't have field 'name', there are only: full_name, address, telephone, email
例2:
some_nums = [1, 2, 3]
print(some_nums[3])
...
IndexError: attempt to get #4 'some_nums' list's elem; it has only 3 elems
我知道我可以在我的程序中将每个方法包装在单独的try-expect块中,并在每个方法的except子句中打印这样的消息。
但它有没有办法收集局部变量数据 ,自动将其传递到顶部单个 try-except块并在那里打印这样的消息?
我在py.test库中看到了类似的东西。 当assert掉到https://pytest.org/latest/assert.html时,它会覆盖内置的python断言并在堆栈跟踪中打印详细消息
如果需要,可以覆盖魔术方法__getattribute__
class HelpfulErrors(object):
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except:
raise AttributeError("class {} doesn't have field '{}', there are only: {}".format(self.__class__.__name__, name, ", ".join(self.__dict__.keys())))
class User(HelpfulErrors):
def __init__(self, age=21):
self.age = age
self.can_drink = self.age >= 21
u = User()
print(u.age)
print(u.can_drink)
print(u.name)
OUTPUT
21
True
Traceback (most recent call last):
File "mes.py", line 18, in <module>
print(u.name)
File "mes.py", line 6, in __getattribute__
raise AttributeError("class {} doesn't have field '{}', there are only: {}".format(self.__class__.__name__, name, ", ".join(self.__dict__.keys())))
AttributeError: class User doesn't have field 'name', there are only: can_drink, age
这实际上只告诉你当前在__dict__
类中的内容,所以这可能会随着时间的推移而改变,除非所有可用的实例成员都是在__init__
完成时定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.