Python:如何打印有关错误的详细错误消息?

时间:2016-04-15 17:58:31

标签: python debugging exception error-handling

我希望获得有关每个变量处理错误的详细信息。

示例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库中看到了类似的东西。它会覆盖内置的python断言,并在断言下降时在堆栈跟踪中打印详细消息 https://pytest.org/latest/assert.html

1 个答案:

答案 0 :(得分:0)

如果您想

,可以覆盖魔术方法__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)

<强>输出

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__完成时定义。 / p>