Decorators in Python!!!

Table of contents

No heading

No headings in the article.

In general term, decorators are those who decorates something to make it prettier. Similarly, In python, decorators are those functions which decorates another function.

Some Information related to python decorators:

  • Decorators takes a function as an argument and returns at another function.
  • Decorators adds new features and functionalities to the existing function.

Usage To add an additional feature to the function without touching that actual function.

Example Let us consider we have a function calculate_area which takes length and breadth as two parameters.

def calculate_area(length, breadth):
    return length*breadth

The above function is an ordinary function which can take negative values as length and breadth in the parameter and can return negative area, which is actually not possible in reality.

area = calculate_area(20,-30)
print("Area is ", area)

Output:- image.png

Now, for the validation, extra new logic has to be written and implemented into that function. Suppose, you have no permission to modify but also have to add new logic in that function, you have to use decorator.

Using decorator, we can write the function as follows,

def validate(func):   # this is the decorator function.
    def inner(length,breadth):
        if length<0 or breadth<0:
            return "Length and breadth field cannot be negative.\n Please enter the valid data."
        return func(length,breadth)
    return inner


@validate
def calculate_area(length, breadth):    #this is the actual function.
    return f"Area is {length*breadth}"

print(calculate_area(20,-30))

Output:-

image.png

In the above function, we have written the decorator function that adds the new functionality to that actual function, that simply validates the input from the user and avoids the invalid input.

In gist, we can say decorators in python is the important function that is useful to add the new functionality to another function.