Categories
Python Answers

How to create decorators with parameters with Python?

Spread the love

Sometimes, we want to create decorators with parameters with Python.

In this article, we’ll look at how to create decorators with parameters with Python.

How to create decorators with parameters with Python?

To create decorators with parameters with Python, we create a function that returns a decorator function.

For instance, we write

def parametrized(dec):
    def layer(*args, **kwargs):
        def repl(f):
            return dec(f, *args, **kwargs)
        return repl
    return layer

to create the parameterized decorator that takes the dec function as its argument.

Then we return the layer function which calls dec.

Next, we can use it by writing

@parametrized
def multiply(f, n):
    def aux(*xs, **kws):
        return n * f(*xs, **kws)
    return aux

@multiply(2)
def function(a):
    return 10 + a

to create a decorator from the multiply function by using the parameterized decorator.

And then we can use the multiply decorator with function.

Conclusion

To create decorators with parameters with Python, we create a function that returns a decorator function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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