Skip to content
Related Articles

Related Articles

Chain Multiple Decorators in Python
  • Last Updated : 08 Jun, 2020

Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.

So, here in this post we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function. It makes decorators useful for resuabale building blocks as it accumulates the several effects together. It is also knows as nested decorators in Python.

Syntax: 

@decor1
@decor
def num():
    statement(s)    

Example: For num() function we are applying 2 decorator functions. Firstly the inner decorator will work and then the outer decorator.

Python3




# code for testing decorator chaining
def decor1(func):
    def inner():
        x = func()
        return x * x
    return inner
  
def decor(func):
    def inner():
        x = func()
        return 2 * x
    return inner
  
@decor1
@decor
def num():
    return 10
  
print(num())

Output:

400

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :