Reputation: 3710
retVal = None
retries = 5
success = False
while retries > 0 and success == False:
try:
retVal = graph.put_event(**args)
success = True
except:
retries = retries-1
logging.info('Facebook put_event timed out. Retrying.')
return success, retVal
In the code above, how can I wrap this whole thing up as a function and make it so that any command (in this example, 'graph.put_event(**args)') can be passed in as a parameter to be executed within the function?
Upvotes: 3
Views: 1229
Reputation: 86854
To directly answer your question:
def foo(func, *args, **kwargs):
retVal = None
retries = 5
success = False
while retries > 0 and success == False:
try:
retVal = func(*args, **kwargs)
success = True
except:
retries = retries-1
logging.info('Facebook put_event timed out. Retrying.')
return success, retVal
This can then be called as such:
s, r = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")
As an aside, given the above task, I would write it along the lines of:
class CustomException(Exception): pass
# Note: untested code...
def foo(func, *args, **kwargs):
retries = 5
while retries > 0:
try:
return func(*args, **kwargs)
except:
retries -= 1
# maybe sleep a short while
raise CustomException
# to be used as such
try:
rv = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")
except CustomException:
# handle failure
Upvotes: 6
Reputation: 798606
def do_event(evt, *args, **kwargs):
...
retVal = evt(*args, **kwargs)
...
Upvotes: 3