python - Python : how to print detailed error messages about errors?

标签 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 assert并在assert下降时在堆栈跟踪中显示详细消息
https://pytest.org/latest/assert.html

最佳答案

如果您想覆盖魔术方法__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__完成时定义了所有将可用的实例成员。

关于python - Python : how to print detailed error messages about errors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653914/

相关文章:

javascript - 如何在 django 上动态更改 block 的内容?

python - 如何停止这个循环?告诉用户他们输入的最长字符串的最佳方式是什么?

java - 为什么我可以查看某些异常的实时调用堆栈,而不能查看其他异常的实时调用堆栈?

c++ - 调试 "Invalid address space"错误

java - SQLException - 无效的游标状态

python - django 获取具有链式外键的对象的查询集

python - 使用 __str__ 打印对象的数组元素

python - 这个程序有什么问题吗?无法调试

java - 共享异常实例是否安全

c++ - 用于在编译前检测 C++ 代码中未捕获异常的静态代码分析工具?