snippetpythonModeratependingCanonical
Python decorator patterns -- timing, retry, and caching
Viewed 0 times
decoratorfunctools.wrapstimingretrymemoizewrapper
python
Problem
Need reusable cross-cutting concerns like timing, retry logic, and caching. Writing them inline clutters business logic.
Solution
Python decorators wrap functions cleanly. Use functools.wraps to preserve the original function metadata.
Code Snippets
Timer and retry decorators
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f'{func.__name__} took {time.perf_counter()-start:.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:
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.