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.

Syntax:

@decorator_function
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.

 

decorators-in-python

 

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.

decorators-in-python

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:
decorators-in-python

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:
decorators-in-python


This is the official syntax to use Decorator Function.

A Very Simple Example to Understand Decorator Function

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

    return inner_decorator

#calling_decorator
@decorator_function
#fun_finds_division_of_number
def main_function():
    print("Normal Function Called")

#calling_normal_function
main_function()

#Output
#Decorator Function Called
#Normal Function Called