retry in python example

Retry in Python Example

Retrying a code block in Python can be very useful in cases where you need to execute a particular task multiple times. There are different ways to implement retries in Python, and we will look at a few examples in this post.

Using a for loop

One of the simplest ways to implement retries is to use a for loop. In this example, we will try to call a function that may fail due to network issues or some other reason. We will try to call this function a maximum of three times before giving up.


import requests
import time

def make_request(url):
    response = None
    for i in range(3):
        try:
            response = requests.get(url)
            break
        except:
            print("Retrying after 5 seconds...")
            time.sleep(5)
    return response

response = make_request("https://www.example.com")
print(response.status_code)
    

In the above example, we try to make a GET request using the requests library. If the request fails, we catch the exception and wait for 5 seconds before trying again. We try a maximum of three times before giving up.

Using the retrying library

The retrying library is a Python library that provides a simple way to implement retries. It provides various options like specifying the maximum number of retries, the backoff factor, and the exception types to catch.


from retrying import retry
import requests

@retry(stop_max_attempt_number=3, wait_fixed=5000)
def make_request(url):
    response = requests.get(url)
    return response

response = make_request("https://www.example.com")
print(response.status_code)
    

In the above example, we use the @retry decorator to specify the maximum number of retries as 3 and the wait time between retries as 5 seconds. The decorator catches any exception raised by the function and retries the function until it succeeds or reaches the maximum number of retries.

Using the tenacity library

The tenacity library is another Python library that provides a simple way to implement retries. It provides various options like specifying the maximum number of retries, the backoff factor, and the exception types to catch.


from tenacity import retry, stop_after_attempt, wait_fixed
import requests

@retry(stop=stop_after_attempt(3), wait=wait_fixed(5000))
def make_request(url):
    response = requests.get(url)
    return response

response = make_request("https://www.example.com")
print(response.status_code)
    

In the above example, we use the @retry decorator to specify the maximum number of retries as 3 and the wait time between retries as 5 seconds. The decorator catches any exception raised by the function and retries the function until it succeeds or reaches the maximum number of retries.