Skip to content

Instantly share code, notes, and snippets.

@dnmellen
Created September 20, 2013 10:42
Show Gist options
  • Save dnmellen/6635803 to your computer and use it in GitHub Desktop.
Save dnmellen/6635803 to your computer and use it in GitHub Desktop.
Calls a function and retries N times if there is an exception or the returned value by the function is *value_to_retry*
def retry(callable, callable_args, num_retries=5, sleep_time=0, value_to_retry='f9e40fdf355643dd82cea787ca2e8d3c04966855'):
"""
Calls a function and retries N times if there is an exception or the returned value by the function is *value_to_retry*
:param callable: What you want to execute
:type callable: python callable obj
:param callable_args: Callable's arguments
:type callable_args: tuple
:param num_retries: Numer of retries
:type num_retries: int
:param sleep_time: Seconds to sleep between retrials
:type sleep_time: int
:param value_to_retry: Checks the return value of the callable and if retry if it's equal
:type value_to_retry: object
In use:
>>> retry(foo, (3, 4), num_retries=10, sleep_time=1)
>>> retry(foo, (3, 4), num_retries=10, sleep_time=1, value_to_retry=None)
>>> retry(foo, tuple(), num_retries=3, sleep_time=5, value_to_retry=False)
"""
for retry in range(num_retries - 1):
try:
return_value = callable(*callable_args)
# Value_to_retry is supposed to be a value that the callable would never return
if value_to_retry != 'f9e40fdf355643dd82cea787ca2e8d3c04966855' and return_value == value_to_retry:
if sleep_time:
time.sleep(sleep_time)
continue
return return_value
except Exception:
if sleep_time:
time.sleep(sleep_time)
return callable(*callable_args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment