不知道这有多可能,但这里有:
我正在尝试用一些稍微微妙的行为来写一个对象 - 这可能是也可能不是一个好主意,我还没有确定.
我有这个方法:
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))
Run Code Online (Sandbox Code Playgroud)
现在,当我像这样创建一个这样的实例时:
t = Thing()
t.foo
Run Code Online (Sandbox Code Playgroud)
我得到一个包含我的函数的stacktrace :
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'
Run Code Online (Sandbox Code Playgroud)
我不希望这样 - 我希望堆栈跟踪读取:
Traceback (most recent call last):
File "attrfun.py", line 23, in <module>
t.foo
AttributeError: 'Thing' object has no attribute 'foo'
Run Code Online (Sandbox Code Playgroud)
这是可能的,只需要很少的努力,还是需要很多种类?我发现这个答案表明看起来有可能,但可能会涉及到.如果有一种更简单的方法,我很乐意听到它!否则我现在就把这个想法放在架子上.
您不能篡改回溯对象(这是一件好事)。你只能控制你如何处理你已经拥有的。
唯一的例外是:您可以
raise e(即使回溯指向重新引发语句的位置)tb_next属性(这反映了一个追逆对象的洋葱状结构)为了您的目的,要走的路似乎是第一个选项:从高于您的函数一级的处理程序重新引发异常。
而且,我再说一遍,这对您自己或将要使用您的模块的任何人都是有害的,因为它会删除有价值的诊断信息。如果您决心以任何理由使您的模块专有,那么将其作为 C 扩展的目标会更有成效。
| 归档时间: |
|
| 查看次数: |
989 次 |
| 最近记录: |