retry2 is a Python library that provides an easy-to-use decorator for retrying functions. It is a fork of the unmaintained `invl/retry` library, offering similar functionality with a focus on being pure standard library Python, though it can optionally preserve function signatures with an additional `decorator` dependency. The current version is 0.9.5.
pip install retry2Verified import paths — ran on the pinned version, not inferred.
This example demonstrates using the `@retry` decorator to automatically retry a function that raises an `IOError`. It will attempt 3 times, with an initial 1-second delay that doubles (backoff=2) between attempts.
Always explicitly set a finite `tries` parameter (e.g., `tries=3`) or `max_delay` to limit retry attempts, especially for operations that are not guaranteed to succeed.
Use `delay` with a positive value and `backoff` (e.g., `backoff=2` for exponential backoff) to introduce increasing delays between retries, giving the downstream service time to recover. Consider adding `jitter` for random variation.
If preserving function signatures is critical for your application or tooling, ensure `pip install decorator` is included in your project's dependencies alongside `retry2`.
Specify the `exceptions` parameter to catch only known transient exceptions (e.g., `(requests.exceptions.ConnectionError, requests.exceptions.Timeout)`). Avoid retrying on generic `Exception` unless absolutely sure.
Design the retried function or the downstream service to handle duplicate requests safely, often by using unique request IDs or transaction identifiers.
Run `pip install retry2` in your terminal to install the package.
Wrap multiple exception types in a tuple, e.g., `@retry(exceptions=(ValueError, TypeError))`.
Change your import statement to `from retry2 import retry` or use `@retry2.retry`.
Update `retry2` to the latest version using `pip install --upgrade retry2`. If the issue persists, review the decorated function for unintended recursion or consider handling timeout logic externally.