gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:59:07 25 4
gpt4 key购买 nike

我想获取有关每个变量处理错误的详细信息。

范例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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com