How to make function decorators and chain them together with Python?

Sometimes, we want to make function decorators and chain them together with Python.

In this article, we’ll look at how to make function decorators and chain them together with Python.

How to make function decorators and chain them together with Python?

To make function decorators and chain them together with Python, we can create decorators that calls the function that’s in the decorator’s parameter in the wrapper function.

Then we return the wrapper function.

For instance, we write:

def bread(func):
    def wrapper(*args, **kwargs):
        print('bread')
        func(*args, **kwargs)
    return wrapper

def ingredients(func):
    def wrapper(*args, **kwargs):
        print("ingredients")
        func(*args, **kwargs)
    return wrapper

@ingredients
@bread
def sandwich(food):
    print(food)

sandwich('tomato')    

top create the bread and ingredients decorators.

They take the func parameter.

The wrapper function takes an indefinite number of arguments as indicated by *args and **kwargs.

We call func in wrapper with *args and **kwargs and return wrapper so func function, which is modified by the decorator is called.

Then we modify sandwich with the ingredients and bread decorators.

And finally, we call sandwich with tomato.

As a result, we get:

ingredients
bread
tomato

logged in the console.

The decorators’ print functions are called before the one in sandwich is called.

Conclusion

To make function decorators and chain them together with Python, we can create decorators that calls the function that’s in the decorator’s parameter in the wrapper function.

Then we return the wrapper function.