Decorator

It is a way to extend the behavior of a function or a method

Example,

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        print("timer starting")
        func()
        end_time = time.time()
        print("timer ending")
        return "time taken to run", end_time -  start_time
    
    return wrapper
    
@timer
def some_process():
    time.sleep(10)
    print("EXECUTING")

ans = some_process()
print(ans)

'''
OUTPUT
timer starting
EXECUTING
timer ending
('time taken to run', 10.000160217285156)
'''    

In the above example,

timer is a decorator that calculates how much time a particular function takes.

some_process can be any function that takes some time. I’ve added 10 seconds delay for example’s sake.

refer args & kwargs if you don’t know what that is.

Updated on