Tuesday, February 25, 2025

Python Decorators

These features of python are not in any order of importance as such.

I chanced upon a youtube video where "the python dude" was explaining decorators.

It seems like in python we can pass function names as parameter.

Also the passed function can be called from the called function.

Hence our code becomes more useful and more difficult to understand.

import time

def measure_time(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

@measure_time
def morning():
    print("Good morning")

morning()

Output:

pythonprgms>python pythonprgm5.py 

Good morning

Execution time 0.000936 sec

A similar program with two decorator per function morning is possible:

#It happens because the decorator runs the function immediately.
# The wrapper prevents that and ensures it only runs when you call it.

import time

def measure_time(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

def greeting(func):
    def wrapper():
        print(f'Hello,')
        func()      
    return wrapper


@greeting
@measure_time
def morning():
    print("Good morning")

morning()

Output:
pythonprgms>python pythonprgm6.py Hello, Good morning
Execution time 0.000936 sec

Similar changes post we can pass arguments to morning function but decorators too need to 
pass same arguments.

# *args , **kwargs
import time

def measure_time(func1):
    def wrapper(*args , **kwargs):
        start = time.time()
        func1(*args , **kwargs)
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

def greeting(func2):
    def wrapper(*args , **kwargs):
        print(f'Hello,')
        func2(*args , **kwargs)      
    return wrapper


@greeting
@measure_time
def morning(name):
    print("Good morning %s" % name)

morning("John P Diaz")

Output:
pythonprgms>python pythonprgm7.py Hello, Good morning John P Diaz Execution time : 0.0 sec