A Decorator Factory in Python 2026

Writing Functions Mar 16, 2026

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 @wraps in 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:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices