In [1]:
import time

Decorators

Decorators provide a way to add functionality to a Python callable object
Form a decorator as:

def decorator_func(func_to_decorate):
    def wrapper_func(*args,*kwargs):
        # Do something here
        result = func_to_decorate(*args,**kwargs)
        # Optionally do something here
        return result
    return wrapper

In [2]:
def decorates(func_to_decorate):
    def wraps(*args):
        print args
        return func_to_decorate(*args)
    return wraps

In [3]:
def about_func(func_to_decorate):
    def wraps(*args,**kwargs):
#         print "{0:*^40s}".format(func_to_decorate.__name__)
        start_time = time.time()
        result = func_to_decorate(*args,**kwargs)
        print "Time taken for {0}() {1:>15f} seconds".format(func_to_decorate.__name__,time.time()-start_time)
        return result
    return wraps

In [4]:
@about_func
def get_sum(a, b=0):
    return a + b

In [5]:
print get_sum(10)


Time taken for get_sum()        0.000003 seconds
10