Retry Decorator
The `retry-decorator` library provides a simple yet powerful decorator for retrying function calls upon specified exceptions. It supports features like setting maximum retries, exponential backoff, and logging failed attempts. Version 1.1.1 is the latest release, with future versions planned to drop Python 2 support. The project appears to be actively maintained, though releases are infrequent.
Warnings
- breaking Version 1.1.1 is the last to officially support Python 2. While minor backports might be considered for Python 2.7, future major versions will likely be Python 3 only, potentially breaking compatibility for older environments.
- gotcha The PyPI package name is `retry-decorator`, but the correct Python import statement is `from python_retry import retry`. Using `from retry_decorator import ...` will result in an `ImportError`.
- gotcha By default, the `@retry()` decorator catches `Exception` (i.e., all exceptions) if the `retry_on` parameter is not explicitly specified. This broad catching can mask unexpected errors in your application logic that should not trigger a retry.
- gotcha There are several Python libraries with similar names and functionality (e.g., `retry`, `retrying`, `retry-reloaded`). Users might accidentally install or import the wrong library, leading to different APIs and unexpected behavior.
Install
-
pip install retry-decorator
Imports
- retry
from retry_decorator import retry
from python_retry import retry
Quickstart
import logging
from python_retry import retry
LOGGER = logging.getLogger(__name__)
@retry(max_retries=3,
backoff_factor=1,
retry_on=(ValueError,),
retry_logger=LOGGER)
def flaky_function():
print("Attempting flaky operation...")
if hasattr(flaky_function, 'calls'):
flaky_function.calls += 1
else:
flaky_function.calls = 1
if flaky_function.calls < 3:
raise ValueError("Simulated transient error")
print("Operation successful!")
return "Success Data"
if __name__ == "__main__":
try:
result = flaky_function()
print(f"Final result: {result}")
except ValueError as e:
print(f"Operation failed after multiple retries: {e}")