Summary: In this tutorial, we will learn what decorator is in Python and how can we use them to modify a function.

Introduction to Decorator

A Decorator in Python is a function that modifies another existing function.

It accepts a function as an argument, wraps it with extra python statements, and returns the newly defined inner function.

In Python, everything is an object, even a function.

Consider the following function for instance:

def add(a, b):
    return a+b
    
print(add(5, 6))   #output 11

It take two numbers as arguments and returns their addition result.

Although the add method only seems to only return the sum of two numbers, we can further increase its functionality by passing it as an argument to another function:

def add(a, b):
    return a+b

#decorator function that modifies the passed function
def my_decorator(func):
    #wrap the passed funtion with a new function
    def modified_func(a, b):
        print("Addition started")
        print(func(a, b))
        print("Addition completed")
    #return the new function
    return modified_func

#getting the modified version using the decorator function
modified_add = my_decorator(add)
#executing the function
modified_add(5, 6)

Output:

Addition started
11
Addition completed

In this example, we passed the add function to the decorator function, defined a new function inside of it, and returned the reference of the new function.

We then get the reference of the new function as modified_add=my_decorator(add) and invoke the same.

A function defined inside another function is known as the inner function.

@ Symbol

Python allows to use decorator in very simple way using a @ symbol.

#decorator function that modifies the passed function
def my_decorator(func):
    #define a new function
    def modified_func(a, b):
        print("Addition started")
        print(func(a, b))
        print("Addition completed")
    #return the new function
    return modified_func

@my_decorator
def add(a, b):
    return a+b

add(5, 6)

Output:

Addition started
11
Addition completed

In this example, we have attached @my_decorator to the add method.

So, when we call the function as add(), the new function returned by the specified decorator (i.e. my_decorator) gets invoked instead.

In short, @my_decorator replaces modified_add=my_decorator(add).

This Post Has One Comment

Leave a Reply

five × one =