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 |
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... |