Sobes.tech
Middle

How to implement a decorator with arguments?

sobes.tech AI

Answer from AI

To create a decorator with arguments, you need to use an additional wrapper. The outer function will accept the decorator arguments, the middle one — the decorated function itself, and the inner — the arguments of the decorated function.

import functools

def decorator_with_args(arg1, arg2):
    # Outer function accepts decorator arguments.
    def actual_decorator(func):
        # Middle function accepts the decorated function.
        @functools.wraps(func)  # Preserves the metadata of the original function.
        def wrapper(*args, **kwargs):
            # Inner function accepts the arguments of the decorated function.
            print(f"Decorator called with arguments: {arg1}, {arg2}")
            print(f"Calling function: {func.__name__}")
            print(f"With arguments: {args}, {kwargs}")
            result = func(*args, **kwargs)
            print(f"Function returned: {result}")
            return result
        return wrapper
    return actual_decorator

# Example usage
@decorator_with_args("hello", 123)
def my_function(a, b):
    return a + b

# Calling the decorated function
print(my_function(5, 7))

When calling @decorator_with_args("hello", 123), first decorator_with_args("hello", 123) is executed. This function returns actual_decorator. Then @ applies actual_decorator to my_function. As a result, my_function is replaced by the wrapper function.

How to implement a decorator with arguments? — Python - sobes.tech