[Python Decorators] Retry

By hientd, at: 2024年7月18日6:00

Estimated Reading Time: 3 min read

[Python Decorators] Retry
[Python Decorators] Retry

Implementing a Retry Decorator in Python


In programming, you often deal with operations that might fail occasionally, such as network requests or database transactions. A retry decorator can help manage these flaky operations by automatically retrying the function if it raises an exception.

 

The Retry Decorator

Here's how you can implement a retry decorator:

from functools import wraps

def retry(exceptions, tries=3):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(tries):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
                    print(f"Attempt {attempt + 1} failed: {e}")
            raise last_exception
        return wrapper
    return decorator

@retry(Exception, tries=3)
def unreliable_function():
    import random
    if random.choice([True, False]):
        raise ValueError("An error occurred")
    return "Success"

try:
    result = unreliable_function()
    print(result)
except Exception as e:
    print(f"Function failed after 3 attempts: {e}")

 

 

Explanation

  1. @wraps(func): This decorator preserves the original function's metadata.
     
  2. retry(exceptions, tries=3): This is the main decorator function. It takes the exceptions to catch and the number of retry attempts as arguments.
     
  3. **wrapper(*args, kwargs): The wrapper function attempts to call the decorated function. If it raises one of the specified exceptions, it retries the function up to the specified number of attempts.

 

Use Cases

  • Network Requests: Automatically retry network requests in case of transient failures.
     
  • Database Operations: Retry database operations that might fail due to temporary issues.
     
  • File Operations: Handle file operations that might fail due to temporary file system issues.

 

Benefits

  • Simplicity: Simplifies error handling by encapsulating retry logic in a decorator.
     
  • Readability: Improves code readability by removing repetitive try-except blocks.
     
  • Flexibility: Allows specifying different exceptions and retry attempts as needed.

 

Conclusion

The retry decorator is a powerful tool for managing flaky operations and improving the robustness of your code. By encapsulating retry logic in a decorator, you can make your code cleaner and more maintainable.

Look at our other decorators:


Subscribe

Subscribe to our newsletter and never miss out lastest news.