Backoff-Utils

1.0.1 · active · verified Thu Apr 16

Backoff-Utils is a Python library that provides functions and decorators for various backoff/retry strategies to Python function and method calls. It offers a consistent syntax and has been tested across a broad range of Python versions, including 2.7, 3.4, 3.5, 3.6, 3.7, and 3.8. The current version is 1.0.1, with recent updates focusing on documentation clarity and dependency management.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both the `backoff()` function and the `@apply_backoff()` decorator. The first example uses `backoff()` to retry an `unreliable_function` with an exponential strategy, catching `ConnectionError`. The second example uses `@apply_backoff()` as a decorator for `another_unreliable_function` with a linear strategy, catching `IOError`. Both include `max_tries` to limit attempts.

import random
import time
from backoff_utils import backoff, apply_backoff, strategies

# Example 1: Using backoff() as a function call
print("\n--- Function Call Example ---")
def unreliable_function(attempt_num):
    print(f"Attempting function (call #{attempt_num})...")
    if random.random() < 0.7: # 70% chance of failure
        raise ConnectionError("Simulated network error")
    return f"Success on attempt {attempt_num}!"

try:
    result_func = backoff(
        unreliable_function, 
        args=[0], # Placeholder, actual attempt num passed internally
        max_tries=5, 
        max_delay=60, 
        strategy=strategies.Exponential,
        catch_exceptions=(ConnectionError,)
    )
    print(result_func)
except ConnectionError as e:
    print(f"Function failed after multiple retries: {e}")

# Example 2: Using @apply_backoff() as a decorator
print("\n--- Decorator Example ---")
@apply_backoff(
    strategy=strategies.Linear(interval=1), 
    max_tries=4, 
    catch_exceptions=(IOError,)
)
def another_unreliable_function(data):
    print(f"Processing '{data}' (decorated function)...")
    if random.random() < 0.5: # 50% chance of failure
        raise IOError("Simulated disk write error")
    return f"Successfully processed '{data}'"

try:
    result_decorator = another_unreliable_function("important data")
    print(result_decorator)
except IOError as e:
    print(f"Decorated function failed after multiple retries: {e}")

view raw JSON →