How do I use a decorator with arguments in Python?

Published on Aug. 22, 2023, 12:16 p.m.

To use a decorator with arguments in Python, you need to define a function that takes the arguments and returns a decorator function, which in turn takes the function that is being decorated as an argument and returns the wrapped function. Here is an example:

def my_decorator(arg1, arg2):
    def the_real_decorator(func):
        def wrapper(*args, **kwargs):
            print(arg1, arg2)
            result = func(*args, **kwargs)
            return result
        return wrapper
    return the_real_decorator

@my_decorator('Hello', 42)
def my_function():
    print('This is my function')

my_function()

In this example, my_decorator takes two arguments and returns another function called the_real_decorator. the_real_decorator takes a function as an argument and returns a wrapped version of the function, which in turn takes arbitrary positional and keyword arguments (*args and **kwargs). When you decorate my_function with @my_decorator('Hello', 42), Python calls my_decorator('Hello', 42) and passes the resulting decorator function to my_function. When you call my_function(), it prints the decorator arguments and then calls the original function.

You can also pass arguments to the decorator when you apply it to a function. Here’s an example:

def my_decorator_with_args(arg1, arg2):
    def the_real_decorator(func):
        def wrapper(*args, **kwargs):
            print(arg1, arg2)
            result = func(*args, **kwargs)
            return result
        return wrapper
    return the_real_decorator

@my_decorator_with_args('Hello', 42)
def my_function_with_args(arg):
    print('This is my function with argument:', arg)

my_function_with_args('John')

In this example, the my_decorator_with_args function is called with arguments when the decorator is applied to my_function_with_args, and the arguments are passed on to the decorator function. The decorator function then returns the wrapper function that takes one positional argument, which is passed on to the original function. When you call my_function_with_args('John'), it prints the decorator arguments and then calls the original function with the 'John' argument.

Tags:

related content