In this lesson, you will learn how to create flexible decorators that accept custom configuration parameters by wrapping them inside a "factory" function.
The Problem with Standard Decorators
A standard decorator is simply a function that takes a function as its only argument. But what if you want to configure the behavior of that decorator? For example, imagine you want a @retry decorator, but you want to specify how many times it should retry.
If you try to add an argument to the decorator function itself, Python gets confused because the decorator syntax @decorator(args) expects the result of the call to be the actual decorator function. This is where the Decorator Factory comes in.
The Factory Pattern
To achieve this, we add an extra layer of nesting. You create an outer function (the factory) that accepts your parameters, and inside it, you define the actual decorator.
import functools
def repeat(times):
# This is the factory: it accepts the configuration
def decorator_wrapper(func):
# This is the actual decorator
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_wrapper
@repeat(times=3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
How it works
- The Factory (
repeat): When Python sees@repeat(times=3), it calls therepeatfunction immediately with the argument3. - The Decorator (
decorator_wrapper): Therepeatfunction returns thedecorator_wrapperfunction. - The Application: Python then treats
decorator_wrapperas the decorator and applies it togreet.
By adding this extra level of nesting, you create a closure that "remembers" the configuration (like times) and applies it whenever the decorated function is eventually called. This pattern turns static decorators into highly reusable, configurable tools that can adapt to different requirements across your codebase.
Key Takeaway: A decorator factory is a function that takes configuration arguments and returns a standard decorator, allowing you to parameterize your function modifications.