HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python decorator patterns — timing, retry, and caching

Submitted by: @anonymous··
0
Viewed 0 times
decoratorfunctools.wrapstimingretrymemoizewrapper
python

Problem

Need reusable cross-cutting concerns like timing, retry logic, and caching. Writing them inline clutters business logic and violates DRY.

Solution

Python decorators wrap functions cleanly. Use functools.wraps to preserve the original function metadata.

Code Snippets

Timer and retry decorators with exponential backoff

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f'{func.__name__} took {elapsed:.4f}s')
        return result
    return wrapper

def retry(max_attempts=3, delay=1):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_attempts - 1:
                        raise
                    time.sleep(delay * (2 ** attempt))
        return wrapper
    return decorator

@timer
@retry(max_attempts=3)
def fetch_data(url):
    ...

Revisions (0)

No revisions yet.