I have a bunch of methods which are quite simple to write, but which all require handling exceptions. Exception management is always the same, so I would like to write a wrapper as a function, to be called with a specific function call instance as parameter. Is it possible?
Something along these lines (this is a non-working illustration):
def g(h):
while True:
try:
x = h()
except:
# got an error
print ("Unexpected error. Retry.")
else:
# everything is fine
return x
def f1(x):
# do something that may fail (e.g. access a distant server)
y = (...whatever...)
return y
def f2(x,y):
# do something else that may fail (e.g. access a distant server, but different request)
z = (...whatever...)
return z
print (g(f1(3)))
print (g(f1(6)))
print (g(f2(5,'abc')))
Note: I am looking for an answer which does not require class definition. Also, I am not familiar with lambda function in python, but could it be part of the solution?
g
:*args
and**kwargs
to allowg
to take the additional parameters that are wanted for your funtions - kindof likeg(f1,3)
andg
needs to pass on stuff to the given function....adding a "retry n times" decorator
to your functions