Open In App
Related Articles

Chain Multiple Decorators in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will try to understand the basic concept behind how to make function decorators and chain them together we will also try to see Python decorator examples

What is Decorator In Python?

A decorator is a function that can take a function as an argument and extend its functionality and return a 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 reusable building blocks as it accumulates several effects together. It is also known as nested decorators in Python. we will also see Python decorator examples.

Syntax of decorator in python

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

Example 1: 

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

Example 2:

For sayhellogfg() and saygfg function, we are applying 2 decorator functions. Firstly the inner decorator(decor1) will work and then the outer decorator(decor2), and after that, the function datawill be printed.

Python3




         
def decor1(func):
        def wrap():
               print("************")
               func()
               print("************")
        return wrap
def decor2(func):
        def wrap():
               print("@@@@@@@@@@@@")
               func()
               print("@@@@@@@@@@@@")
        return wrap
     
@decor1
        
@decor2
def sayhellogfg():
         print("Hello")
def saygfg():
         print("GeekforGeeks")
         
sayhellogfg()
saygfg()


Output:

************
@@@@@@@@@@@@
Hello
@@@@@@@@@@@@
************
GeekforGeeks

You can also learn about Genetator in Python.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials