A Decorator Factory in Python 2026 – Best Practices
A **decorator factory** is a function that returns a decorator. It allows you to create configurable decorators that accept arguments. This is one of the most powerful and commonly used patterns when writing advanced decorators in modern Python.
TL;DR — Structure of a Decorator Factory
- Outermost function receives the decorator arguments
- Middle function is the actual decorator
- Innermost function is the wrapper that runs around the original function
- Always use
@wrapsin the wrapper
1. Classic Decorator Factory Example
from functools import wraps
from typing import Callable, Any
def repeat(times: int = 2):
"""Decorator factory that repeats the function 'times' times."""
def decorator(func: Callable) -> Callable:
"""The actual decorator."""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
"""The wrapper that gets called instead of the original function."""
result = None
for i in range(times):
print(f"Execution {i+1} of {times} for {func.__name__}()")
result = func(*args, **kwargs)
return result
return wrapper
return decorator
2. Real-World Usage
@repeat(4)
def roll_dice():
import random
return random.randint(1, 6)
@repeat(3)
def greet(name: str):
print(f"Hello {name}!")
roll_dice()
greet("Alice")
3. Another Useful Example – delay Decorator Factory
import time
def delay(seconds: float = 1.0):
"""Decorator factory that adds a delay before running the function."""
def decorator(func: Callable):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Waiting {seconds} seconds before running {func.__name__}()...")
time.sleep(seconds)
return func(*args, **kwargs)
return wrapper
return decorator
@delay(0.5)
def send_notification(message: str):
print(f"Notification sent: {message}")
4. Best Practices for Decorator Factories in 2026
- Give the outer function a clear, descriptive name (e.g., `repeat`, `delay`, `retry`)
- Always include sensible default values for parameters
- Use
@wraps(func)in the innermost wrapper - Validate arguments early in the factory function
- Keep the wrapper logic lightweight and fast
- Document what each argument controls
Conclusion
A decorator factory is the standard way to create configurable, reusable decorators in Python. In 2026, mastering this pattern allows you to build powerful tools like retry mechanisms, rate limiters, caching decorators, and logging utilities with minimal code duplication.
Next steps:
- Convert one of your simple decorators into a decorator factory with parameters
- Related articles: Decorators That Take Arguments in Python 2026 • Decorators in Python 2026 • Writing Functions in Python 2026