Decorator Factory in Python

Level 5505 keystrokes

This creates a parameterized decorator factory for retry logic with configurable attempts and exception types.

Python code

# wraps copies the original function's name and docstring to the wrapper
1from functools import wraps
2
# def retry is the decorator factory with parameters
3def retry(max_attempts=3, exceptions=(Exception,)):
# def decorator is the actual decorator
4 def decorator(func):
# @wraps preserves original function's metadata
5 @wraps(func)
# wrapper is the function that replaces the original
6 def wrapper(*args, **kwargs):
# Loop through each attempt
7 for attempt in range(1, max_attempts + 1):
# Try to execute the function
8 try:
# Return result if successful
9 return func(*args, **kwargs)
# Catch specified exceptions
10 except exceptions as e:
# Re-raise if this was the last attempt
11 if attempt == max_attempts:
12 raise
# Log the failed attempt
13 print(f"Attempt {attempt} failed: {e}")
# Return the wrapper function
14 return wrapper
# Return the decorator
15 return decorator
16
# Apply decorator with custom parameters
17@retry(max_attempts=2, exceptions=(ValueError,))
# Define a function that may fail
18def risky_operation(x):
# Raise ValueError for negative numbers
19 if x < 0:
20 raise ValueError("Negative!")
# Return double the value for 0 and positive numbers
21 return x * 2
22
# 5 succeeds on the first attempt, so 10 is printed
23print(risky_operation(5))

Output

10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 14
  • )× 14
  • :× 10
  • ,× 7
  • *× 7
  • _× 6
  • =× 6
  • "× 4
  • {× 2
  • }× 2

More Python examples at level 5

← Python typing practice