Reretry

0.11.8 · active · verified Thu Apr 16

Reretry is a Python library providing an easy-to-use, yet functional decorator for retrying functions on exceptions. It is a fork of the `retry` package, enhancing it with features like logging of traceback, callbacks after each failure, and support for `async` functions. Currently at version 0.11.8, it is actively maintained with a focus on providing a robust retry mechanism with minimal dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both synchronous and asynchronous usage of the `@retry` decorator. The `flaky_sync_function` will retry up to 3 times with a 1-second delay on `ValueError`, while `flaky_async_function` retries twice with a 0.5-second delay on `RuntimeError`. The `asyncio.run()` is used to execute the asynchronous example.

import random
import asyncio
from reretry import retry

attempt_count = 0

@retry(exceptions=ValueError, tries=3, delay=1)
def flaky_sync_function():
    global attempt_count
    attempt_count += 1
    print(f"Sync function attempt {attempt_count}...")
    if random.randint(1, 10) < 7:
        raise ValueError("Sync operation failed!")
    print("Sync operation succeeded!")
    return "Success"

async_attempt_count = 0

@retry(exceptions=RuntimeError, tries=2, delay=0.5)
async def flaky_async_function():
    global async_attempt_count
    async_attempt_count += 1
    print(f"Async function attempt {async_attempt_count}...")
    if random.randint(1, 10) < 8:
        raise RuntimeError("Async operation failed!")
    print("Async operation succeeded!")
    return "Async Success"

if __name__ == "__main__":
    print("\n--- Running Synchronous Example ---")
    try:
        result_sync = flaky_sync_function()
        print(f"Final sync result: {result_sync}")
    except Exception as e:
        print(f"Sync function ultimately failed: {e}")

    print("\n--- Running Asynchronous Example ---")
    try:
        result_async = asyncio.run(flaky_async_function())
        print(f"Final async result: {result_async}")
    except Exception as e:
        print(f"Async function ultimately failed: {e}")

view raw JSON →