Wondering how to retry a function in python, even if it complains with exceptions?
I created a retry decorator which will help a function get called multiple times even if a set of exceptions are thrown.
The decorator will
- Catch the exceptions if thrown and retry the function
- Introduce a delay specified between successive calls
- Eventually (after the last retry), throw the exception if the function keeps on throwing the exception after multiple retries
Scenarios – This decorator can come handy if you are trying to write some kind of file downloader form certain api where read/connect timeouts may occur.
Here it is:
def retry(exceptions, delay=0, times=2): """ A decorator for retrying a function call with a specified delay in case of a set of exceptions Parameter List ------------- :param exceptions: A tuple of all exceptions that need to be caught for retry e.g. retry(exception_list = (Timeout, Readtimeout)) :param delay: Amount of delay (seconds) needed between successive retries. :param times: no of times the function should be retried """ def outer_wrapper(function): @functools.wraps(function) def inner_wrapper(*args, **kwargs): final_excep = None for counter in xrange(times): if counter > 0: time.sleep(delay) final_excep = None try: value = function(*args, **kwargs) return value except (exceptions) as e: final_excep = e pass #or log it if final_excep is not None: raise final_excep return inner_wrapper return outer_wrapper @retry(exceptions=(TimeoutError, ConnectTimeoutError), delay=0, times=3) def download_gd_file():
#Note – The exception names above are symbolic 🙂
Hope you find it useful 😀