How to pass parameters to decorators in Python?

In Python, decorators can accept parameters by wrapping the decorator function with another function outside it. For example:

def my_decorator(param):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print("Decorator with param: {}".format(param))
            return func(*args, **kwargs)
        return wrapper
    return decorator

@my_decorator("Hello")
def say_hello():
    print("Hello, world!")

say_hello()

In the example above, my_decorator is a decorator function that takes parameters. When using the decorator, you can pass arguments to my_decorator, which will then return a decorator function called decorator. This decorator function takes the decorated function as a parameter and returns a new function called wrapper that wraps the original function. Inside the wrapper function, we can use the arguments passed to my_decorator.

 

More tutorials

How to use decorators to decorate functions in Python?(Opens in a new browser tab)

What is the purpose of a double pointer in the C language?(Opens in a new browser tab)

What is the usage of resize in C++?(Opens in a new browser tab)

How can we use strlen in C language to calculate the length of an array?(Opens in a new browser tab)

What are the potential reasons for JMX not working in Java?(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *