下似乎做你所描述的:
def retry_if_exception(exception, max_retries=2):
def _retry_if_exception(method_fn):
# method_fn is the function that gives rise
# to the method that you've decorated,
# with signature (slf, foo)
from functools import wraps
def method_deco(slf, foo):
tries = 0
while True:
try:
return method_fn(slf, foo)
except exception:
tries += 1
if tries > max_retries:
raise
return wraps(method_fn)(method_deco)
return _retry_if_exception
下面是它在使用中的例子:
d = {}
class Foo():
def usually_raise_KeyError(self):
print("d[17] = %s" % d[17])
foo1 = Foo()
class A():
@retry_if_exception(KeyError, max_retries=2)
def something_that_sometimes_fails(self, foo):
print("About to call foo.usually_raise_KeyError()")
foo.usually_raise_KeyError()
a = A()
a.something_that_sometimes_fails(foo1)
這給:
About to call foo.usually_raise_KeyError()
About to call foo.usually_raise_KeyError()
About to call foo.usually_raise_KeyError()
Traceback (most recent call last):
File " ......... TrapRetryDeco.py", line 39, in <module>
a.something_that_sometimes_fails(foo1)
File " ......... TrapRetryDeco.py", line 15, in method_deco
return method_fn(slf, foo)
File " ......... TrapRetryDeco.py", line 36, in something_that_sometimes_fails
foo.usually_raise_KeyError()
File " ......... TrapRetryDeco.py", line 28, in usually_raise_KeyError
print("d[17] = %s" % d[17])
KeyError: 17
我認爲通過「2次重試」你的意思是手術將嘗試3次全部告訴。你的例子有一些複雜的可能會掩蓋基本的設置: 看來你想要一個方法裝飾器,因爲你的函數/方法的第一個參數是「self」;然而,該方法立即委託給它的foo參數的一些不好的方法。我保留了這些併發症:)
接受換行說明 –