Open In App
Related Articles

Nested Decorators in Python

Improve Article
Save Article
Like Article

Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. 

Nesting means placing or storing inside the other. Therefore, Nested 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 the several effects together.

How several decorators are applied?

A function can be decorated multiple times. We need to define the decorator first that we want to wrap the output string with, and then apply them to the function using the ‘@’ . One simply needs to place the decorators above the desired function.

Syntax :

def function(name):

Nested decorators follow a bottom to top approach i.e the reverse order. It can be related to a construction of  building where we start the construction from the bottom (the ground) and then start building the floors.

Example :


# Python program to demonstrate
# nested decorators
def italic(func):
    def wrapper():
        return '<i>' + func() + '</i>'
    return wrapper
def strong(func):
    def wrapper():
        return '<strong>' + func() + '</strong>'
    return wrapper
def introduction():
    return 'This is a basic program'


<i><strong>This is a basic program</strong></i>

Explanation :

  1. We have defined two decorators first, which are used in wrapping the output string of the decorated function in the ‘strong’ and ‘italic’ tags of HTML.
  2. Then we are applying the two decorators to our ‘introduction’ function by using just an “@” and the function name. For example in this program we are using @italic and @strong.
  3. The hierarchy that it follows is from bottom to top. Therefore according to it the string is wrapped with ‘strong’ first an then with ‘italic’.
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 : 25 Aug, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials