我想在Python中实现一个可以存储在某处的延迟异常,但是一旦以任何方式使用它,它就会引发延迟的异常。像这样:
# this doesn't work but it's a start
class DeferredException(object):
def __init__(self, exc):
self.exc = exc
def __getattr__(self, key):
raise self.exc
# example:
mydict = {'foo': 3}
try:
myval = obtain_some_number()
except Exception as e:
myval = DeferredException(e)
mydict['myval'] = myval
def plus_two(x):
print x+2
# later on...
plus_two(mydict['foo']) # prints 5
we_dont_use_this_val = mydict['myval'] # Always ok to store this value if not used
plus_two(mydict['myval']) # If obtain_some_number() failed earlier,
# re-raises the exception, otherwise prints the value + 2.
用例是我想编写代码来分析传入数据中的一些值;如果此代码失败但结果从未使用过,我希望它安静地失败;如果它失败但结果稍后使用,那么我希望失败能够传播。你知道吗
有什么建议吗?如果使用DeferreException类,则得到以下结果:
>>> ke = KeyError('something')
>>> de = DeferredException(ke)
>>> de.bang # yay, this works
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __getattr__
KeyError: 'something'
>>> de+2 # boo, this doesn't
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'DeferredException' and 'int'
阅读文档的第3.4.12节“新样式类的特殊方法查找”,它准确地解释了您遇到的问题。对于某些操作符(如addition),解释器会绕过常规的属性查找(正如您发现的困难方法)。因此,代码中的语句de+2从不调用getattr函数。你知道吗
根据该节,唯一的解决方案是确保“必须在类对象本身上设置特殊方法,以便解释器一致地调用。”
也许您最好将所有延迟的异常存储在一个全局列表中,将整个程序包装在一个尝试:终于:语句,并在finally块中打印出整个列表。你知道吗
相关问题 更多 >
编程相关推荐