Skip to main content

Python: Decorators

In Python, decorators allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. It takes in a function, adds some functionality and returns it.

This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time. Decorators, functions are taken as the argument into another function and then called inside the wrapper function.

Example:

In this example, we can easily find out the execution time of a function using a decorator.

import time
import math
  
def calculate_time(func):
    def inner1(*args, **kwargs):
        begin = time.time()
        func(*args, **kwargs)
        end = time.time()
        print("Total time taken in: ", func.__name__, end - begin)
    return inner1

@calculate_time
def factorial(num):
    time.sleep(2)
    print(math.factorial(num))

factorial(10)

Output:

3628800
Total time taken in :  factorial 2.004849910736084
Tags
Submitted by devanshi.srivastava on July 5, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.