Sobes.tech
Middle

How to write a decorator in Python that accepts parameters?

sobes.tech AI

Answer from AI

A decorator that accepts parameters is implemented using an additional outer factory function. This function takes the decorator parameters and returns the decorator itself.

def parameterized_decorator(param1, param2):
    # Decorator factory: accepts decorator parameters

    def decorator(func):
        # The decorator itself: accepts the function to be decorated

        def wrapper(*args, **kwargs):
            # Wrapper: executes logic before and after calling the decorated function
            print(f"Decorator parameters: {param1}, {param2}")
            print(f"Calling function: {func.__name__} with arguments: {args}, {kwargs}")
            result = func(*args, **kwargs)
            print(f"Function result: {result}")
            return result

        return wrapper

    return decorator

# Using the decorator with parameters
@parameterized_decorator("value1", 123)
def my_function(a, b):
    return a + b

# Calling the decorated function
my_function(5, 10)

Step-by-step explanation:

  1. parameterized_decorator(param1, param2): This is a decorator factory function. It accepts parameters that will be passed to the decorator when applied (@parameterized_decorator("value1", 123)). It returns the decorator itself (decorator).
  2. decorator(func): This function acts as the actual decorator. It accepts the function to be decorated (my_function in the example) as an argument. It returns a wrapper function (wrapper).
  3. wrapper(*args, **kwargs): This function replaces the original decorated function during execution. It accepts any positional (*args) and keyword (**kwargs) arguments passed during the call. Inside, it implements the decorator logic (printing decorator parameters, call info, and result). The original function is called via func(*args, **kwargs).

Key points:

  • An additional outer function is needed to pass parameters.
  • This outer function returns a function that is the "real" decorator.
  • The real decorator returns a wrapper function containing the decorator logic and calling the original function.
  • The syntax @parameterized_decorator(param1, param2) when applied automatically calls the factory function (parameterized_decorator) with the specified parameters, then applies the returned decorator to the next line (the decorated function).