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.py1157 chars33 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.py156 chars7 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