Python Retrying Library
Retrying is an Apache 2.0 licensed general-purpose Python library designed to simplify the task of adding retry behavior to functions. It allows developers to configure retry logic for transient failures, specifying stop conditions, wait strategies (like exponential backoff), and conditions for retrying based on exceptions or return values. The current version is 1.4.2.
Warnings
- breaking The `retrying` library is generally considered unmaintained. Its active development ceased some time ago, and `tenacity` is an actively developed fork that addresses shortcomings and adds new features. Users are strongly encouraged to migrate to `tenacity` for ongoing support, bug fixes, and new capabilities.
- gotcha The default behavior of the `@retry` decorator is to retry *forever* on any exception, with *no delay* between attempts. This can lead to infinite loops, high CPU usage, and rapid resource exhaustion in production systems if not explicitly configured with stop and wait strategies.
- gotcha Older examples or documentation for `retrying` (especially from its earlier development stages) might use Python 2 `print` syntax (e.g., `print "message"`). Since the library now requires Python 3.6+, ensure all `print` statements use the function syntax (`print("message")`).
Install
-
pip install retrying
Imports
- retry
from retrying import retry
- stop_after_attempt
from retrying import stop_after_attempt
- wait_fixed
from retrying import wait_fixed
- wait_exponential
from retrying import wait_exponential
Quickstart
import random
import os
from retrying import retry, stop_after_attempt, wait_fixed
@retry(stop_max_attempt_number=5, wait_fixed=1000) # Retry up to 5 times, waiting 1 second between attempts
def do_something_unreliable():
if random.randint(0, 10) > 2: # Simulate a failure 70% of the time
print("Operation failed, retrying...")
raise IOError("Simulated transient error")
else:
print("Operation successful!")
return "Awesome sauce!"
try:
result = do_something_unreliable()
print(f"Final result: {result}")
except IOError as e:
print(f"Operation failed after multiple retries: {e}")