

Decorator in Python

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
Output:
The @my_decorator
wraps say_hello
— without modifying its original logic!
How Decorator Works
@decorator
is syntactic sugar for:
Decorators use closures (a function inside another function) to wrap and enhance behavior.
Common Use Cases
Use Case | Example Decorator |
Logging |
|
Timing |
|
Authorization |
|
Caching |
|
Input validation |
|
Decorators with Arguments
Output:
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 |