How to implement decorators in python?



Introduction

Decorators in python wrap a function and modify its behavior in one way or other without having to directly change the source code of the function being decorated.

Implementing decorators in python

Example 1:

# result.py

import time
def decorator(func):
    def inner():
        print("Congratulations......")
        time.sleep(2)
        func()
        print("Promoted to next level.")
    return inner
def exam():
    print("You are passed!")
    
result = decorator(exam)
result()

Output:

Congratulations......
You are passed!
Promoted to next level.


Example 2:

# div.py

def div(x,y):
    print(f"Division of two number is {x/y}")

def div_modifier(func):
    
    def inner_work(a,b):
        if a < b:
            a,b = b,a
            return func(a,b)
        else:
            func(a,b)
    return inner_work
    
result = div_modifier(div)
result(2, 8)

Output:

Division of two number is 4.0

Previous post: JSON in python

In-depth lesson on decorators by geeks for geeks