Decorators in Python | Python Programming

Decorators: Decorators in Python are special type of function used to enhance the functionality of existing function or other function. Decorators can also be used to modify callable objects like functions, methods or classes. We will deal with functions in this tutorial.


def normalFunction():
    return "any_statement"

Here @decorator_function is the name of decorator function (user defined). We define decorator function and add all the functionality to it that we want to add in our normal function. For now, just forget about that syntax. Will explain later after discussing some important points.




Important: Decorators are used in python to enhance the functionality of other function without changing its (other’s function) code.

Example 1: Suppose we have a function which finds the division of two numbers.


So above given program finds the division of two number. But point to note, that the functionality of function depends upon the value passed to the function. If user pass wrong value like 2,4 instead of 4,2 that we have passed. Then in that case the output will be 0.5. No doubt output is correct.

But if we want to write a code in such a way, that without doing any modification in our main function we add a feature to our function which checks for the value passed to a and b. If value of a is smaller than b, then it swap the value of a to b and value of b to a. And then return the final output after division.

This can only be possible by using Decorators.

Example 2:

Explanation: The only new thing in our above example is the decorator function definition. so, let’s discuss how we defined our decorator function.

Decorator function takes normal function (the function which we want to modify) as an argument. In inner_decorator function, we adds the functionality that we actually want to add in our main function. The value returned by inner_decorator function sent to our main_function. Hence decorator checks for condition

I will also show one very simple example on decorators at the end.

@decorator_function is the shortcut method to use decorator function. We can call decorator function just before any function where we want to add decorator’s functionality.  Follow below given example:

Example 3:

This is the official syntax to use Decorator Function.

A Very Simple Example to Understand Decorator Function

def decorator_function(main_function):
    def inner_decorator():
        print("Decorator Function Called")

    return inner_decorator

def main_function():
    print("Normal Function Called")


#Decorator Function Called
#Normal Function Called