Skip to main content

What are Decorators in Python

In our previous Python tutorial, we have explained how to Automate Everything with Python. In this tutorial, you will learn about Decorators in Python.

In python, Decorators is a design pattern that allows to modify the functionality of a function by wrapping it in another function. It takes the original function as an argument and returns as extended version of it, means without permanently modifying it.

In Python, functions are treated as objects which means that functions can be used or passed as arguments.

Let’s proceed to know how decorators works:

For example, we have a Python program with two function like below.

import time

def getEmployeee():
    print("Employee: Any Smith");
    time.sleep(1.3)

def getSalary():
    print("Salary: $7000")
    time.sleep(.4)

getEmployeee();
getSalary();

Output:

Employee: Any Smith
Salary: $7000

When we run above program, it will print employee details and salary. Now if we want to know how much execution time taken by each function, generally we need to write function for each one. What if there are hundreds or thousands of functions to get execution time. Simply, we can write Decorators function to achieve this.

We ca easily find out the execution time of each function using a decorator. In below example code, we have created calculateTime() decorator and define a wrapper() function to get function execution time and print it.

The decorator are called by adding @ symbol before decorator function. We can decorate the function by adding decorator just before a function to use it.

import time

def calculateTime(func):
    def wrapper():
        t1 = time.time()
        func()
        t2 = time.time() - t1        
        print(f'The function {func.__name__} ran in {t2} seconds\n')
    return wrapper
	
# decorate the function
@calculateTime
def getEmployeee():
    print("Employee: Any Smith");
    time.sleep(1.3)

# decorate the function
@calculateTime
def getSalary():
    print("Salary: $7000")
    time.sleep(.4)

getEmployeee();
getSalary();

Output:

Employee: Any Smith
The function getEmployeee ran in 1.3008148670196533 seconds

Salary: $7000
The function getSalary ran in 0.4007551670074463 seconds

In above example, we have added decorators @calculateTime before functions and getting functions execution time.