gpt4 book ai didi

python - 如何在 Python 中创建一个减去最后一个堆栈帧的异常?

转载 作者:太空狗 更新时间:2023-10-30 00:10:41 26 4
gpt4 key购买 nike

不确定这有多大可能,但这里是:

我正在尝试编写一个具有稍微更微妙行为的对象 - 这可能是也可能不是一个好主意,我还没有确定。

我有这个方法:

def __getattr__(self, attr):                                                                                                      
try:
return self.props[attr].value
except KeyError:
pass #to hide the keyerror exception

msg = "'{}' object has no attribute '{}'"
raise AttributeError(msg.format(self.__dict__['type'], attr))

现在,当我像这样创建一个这样的实例时:

t = Thing()
t.foo

我得到一个包含我的函数的堆栈跟踪:

Traceback (most recent call last):
File "attrfun.py", line 23, in <module>
t.foo
File "attrfun.py", line 15, in __getattr__
raise AttributeError(msg.format(self._type, attr))
AttributeError: 'Thing' object has no attribute 'foo'

我不想要那个 - 我想要堆栈跟踪读取:

Traceback (most recent call last):
File "attrfun.py", line 23, in <module>
t.foo
AttributeError: 'Thing' object has no attribute 'foo'

这是否可以通过最少的努力实现,还是需要付出很多努力?我找到了 this answer这表明某些事情看起来是可能的,尽管可能涉及。如果有更简单的方法,我很想听听!否则我会暂时搁置这个想法。

最佳答案

您不能篡改回溯对象(这是一件好事)。您只能控制如何处理您已经拥有的。

唯一的异常(exception)是:你可以

就您的目的而言,要走的路似乎是第一个选项:从函数上一级的处理程序重新引发异常。

而且,我再说一遍,这对您自己或将使用您的模块的任何人都是有害的,因为它会删除有值(value)的诊断信息。如果您出于任何理由都坚持让您的模块专有,那么将其作为 C 扩展会更有成效。

关于python - 如何在 Python 中创建一个减去最后一个堆栈帧的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26993675/

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