Decorator in Python

Vaibhav Singh
Posted on 23rd Jun 2025 6:19 PM | 10 min Read | 60 min Implementation

#python #decorator #closure #logging #authorization #cache

What is a Decorator in Python?


A decorator in Python is a function that modifies the behaviour of another function, method, or class, without changing its actual code. It's like putting a filter, wrapper, or enhancer around your function.



Real-Life Analogy


Imagine your function is a plain dosa.
The decorator is the masala filling and chutney you wrap around it.
Same dosa, but now it’s "Masala Dosa Deluxe"



Basic Decorator Example


def my_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper

@my_decorator
def say_hello():
print("Hello, Vaibhav!")

say_hello()


Output:


Before the function runs
Hello, Vaibhav!
After the function runs


The @my_decorator wraps say_hello — without modifying its original logic!




How Decorator Works


@decorator is syntactic sugar for:


say_hello = my_decorator(say_hello)


Decorators use closures (a function inside another function) to wrap and enhance behavior.





Common Use Cases



Use Case

Example Decorator

Logging

@log

Timing

@timeit

Authorization

@login_required

Caching

@lru_cache from functools

Input validation

@validate_json


Decorators with Arguments


def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator

@repeat(3)
def cheer():
print("Python Rocks!")

cheer()


Output:

Python Rocks!
Python Rocks!
Python Rocks!


Summary


Decorator Is...

Meaning

A wrapper

Enhances a function without changing its source

Reusable

Can be applied to many functions

Flexible

Can accept arguments

Readable

Makes cross-cutting concerns (logging, auth, etc.) cleaner


All Comments ()
Do You want to add Comment in this Blog? Please Login ?