Hey everybody I\'m working on a data scraping project and I\'m looking for a clean way to repeat a function call if an exception is raised.
Pseudo-code:
To do precisely what you want, you could do something like the following:
import functools
def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
@functools.wraps(fn) #keeps name and docstring of old function
def new_fn(*args, **kwargs):
for i in xrange(x):
try:
return fn(*args, **kwargs)
except exceptions_to_catch:
pass
raise exception_to_raise
return new_fn
Then you just wrap the old function in this new function:
#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')
#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')