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 wrapper1from functools import wraps2 # def retry is the decorator factory with parameters3def retry(max_attempts=3, exceptions=(Exception,)): # def decorator is the actual decorator4 def decorator(func): # @wraps preserves original function's metadata5 @wraps(func) # wrapper is the function that replaces the original6 def wrapper(*args, **kwargs): # Loop through each attempt7 for attempt in range(1, max_attempts + 1): # Try to execute the function8 try: # Return result if successful9 return func(*args, **kwargs) # Catch specified exceptions10 except exceptions as e: # Re-raise if this was the last attempt11 if attempt == max_attempts:12 raise # Log the failed attempt13 print(f"Attempt {attempt} failed: {e}") # Return the wrapper function14 return wrapper # Return the decorator15 return decorator16 # Apply decorator with custom parameters17@retry(max_attempts=2, exceptions=(ValueError,))# Define a function that may fail18def risky_operation(x): # Raise ValueError for negative numbers19 if x < 0:20 raise ValueError("Negative!") # Return double the value for 0 and positive numbers21 return x * 222 # 5 succeeds on the first attempt, so 10 is printed23print(risky_operation(5))Output
10
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