create a retry decorator for when the function fails in python

To create a retry decorator for when a function fails in Python, we can use a decorator function that takes a function as its argument, and returns a new function that calls the original function, and if it raises an exception, retries the function a specified number of times with a specified delay between retries.

main.py
import time

def retry(exception_to_check, tries=4, delay=3, backoff=2):
    """
    Retry calling the decorated function using an exponential backoff.

    Args:
        exception_to_check (Exception): The exception to check. may be a tuple of exceptions to check
        tries (int): Number of times to try (not retry) before giving up.
        delay (int): Initial delay between retries in seconds.
        backoff (int): Backoff multiplier e.g. value of 2 will double the delay each retry.

    Returns:
        The result of the decorated function.

    """
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            m_tries, m_delay = tries, delay
            while m_tries > 1:
                try:
                    return f(*args, **kwargs)
                except exception_to_check as e:
                    msg = f"{str(e)}, Retrying in {m_delay} seconds..."
                    print(msg)
                    time.sleep(m_delay)
                    m_tries -= 1
                    m_delay *= backoff
            # last attempt
            return f(*args, **kwargs)
        return f_retry  # true decorator
    return deco_retry
1157 chars
33 lines

The above snippet defines a retry decorator that takes the type of exception to check (or a tuple of exceptions), the number of retries, the delay between retries, and the backoff factor, and returns a decorator that can be used to wrap any function and provide retries in case of exception.

Usage:

main.py
# example usage of retry decorator

@retry((ConnectionError, TimeoutError), tries=3, delay=2, backoff=2)
def fetch_data(url):
    # your code here
    pass
156 chars
7 lines

In the above example, the fetch_data function is decorated with @retry. The decorator specifies that the function should be retried in case of either ConnectionError or TimeoutError, with a maximum of 3 tries, a starting delay of 2 seconds, and a backoff factor of 2 (meaning the delay between retries doubles after each retry).

gistlibby LogSnag