Easy and neat way to retry function after error in Python

Have you ever written a Python script that needed to handle unreliable network connections or flaky APIs? If so, you might have encountered situations where your script would fail due to transient errors such as network timeouts, HTTP 500 errors, or rate limits. In these cases, it can be helpful to automatically retry the failing operation instead of giving up and terminating the script. This is where the tenacity library comes in.

tenacity is a Python library that provides a flexible and powerful way to retry operations that might fail due to various reasons. With tenacity, you can retry a function with configurable delay intervals, maximum retries, and exception handling. You can also customize the retry behavior based on the return value of the function.

Let’s take a look at a simple example here:

import random
from tenacity import retry, stop_after_attempt, wait_random

@retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=5))
def my_func():
if random.random() > 0.3:
print("Random number > 0.3, function succeeded!")
print("Random number <= 0.3, raising ValueError...")
raise ValueError("Random number is too low.")


one of the output may like this, where you can see it fails for two time, then succeeded at the 3rd try:

Random number <= 0.3, raising ValueError...
Random number <= 0.3, raising ValueError...
Random number > 0.3, function succeeded!

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !