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