Course contentsShow
← Python
Lesson 610 of 1,06010. Advanced Language FeaturesFree lesson

Passing Arguments to Decorators via Factories

Implement decorator factories to accept configuration parameters, allowing for highly reusable and customizable function modification logic.

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

  1. The Factory (repeat): When Python sees @repeat(times=3), it calls the repeat function immediately with the argument 3.
  2. The Decorator (decorator_wrapper): The repeat function returns the decorator_wrapper function.
  3. The Application: Python then treats decorator_wrapper as the decorator and applies it to greet.

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.