Let’s start with something simple..What is a decorator?

According to python.org, “A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated”

A classic example tat I can think of right now is related to performance. What if we have requirement to calculate the total time taken by a method to perform its operations. Will you always end up writing code for getting the time difference for every method call you make? Well, yes if I had to do it for 4-5 methods, but what if I have to do for 50s or 60s of methods across my Python code? Then? Python decorators come to the rescue.

How? You could write a simple Python decorator method that:

1. Gets the start time

2. Calls the method for which the time taken has to be calculated

3. Gets the time when the method has completed its computation

4. Prints the time difference between end time (3) and start time (1)

Simple! Let’s see some code

from datetime import datetime
def decorate(f):
    start = datetime.now()
    end = datetime.now()
    print end-start

def fact(n):
    fact = 1
    for i in range(1,n+1):
        fact *= i

## Decorator on argument function

from datetime import datetime

def timer(fn):
 first = datetime.now()
 sec = datetime.now()
 print sec-first

def fn(*args):
 for i in range(args[0]):

Output of this code snippet is 0:00:00.006000 (time taken to calculate factorial of 3000 on my system)