Python Decorators
What is a Decorator?
A decorator is a function that adds extra functionality to another function without changing the original function's code.
Think of it like decorating a plain cake:
Original cake → Add cream → Add chocolate → Decorated Cake
The cake is still the same cake. We just added extra features.
Original function → Decorator → Function + Extra Behavior
def withdraw_money():
print("Money Withdrawn")
Instead of modifying
withdraw_money() every time, we can create decorators.
Functions are First-Class Objects
In Python, functions are first-class objects. This means:
- We can store a function in a variable
- We can pass a function as an argument
- We can return a function from another function
def greet():
print("Good morning")
x = greet
x()
Good morning
x = greet (we did not write x = greet())greet means the function itselfgreet() means execute the function
Passing a Function to Another Function
def greet():
return "Good Morning"
def display(func):
print(func()) # executes the function that was passed
display(greet) # passes the greet function itself
Good Morning
Function Inside Another Function
Python allows nested functions.
def outer():
def inner():
print("Inside inner function")
inner()
outer()
Inside inner function
Returning a Function
A function can also return another function.
def outer():
def inner():
print("Hello from inner function")
return inner
x = outer() # outer() has finished, but inner() is still available
x()
Hello from inner function
What is a Closure?
A closure happens when an inner function remembers information from its outer function even after the outer function has completed.
def outer(name):
def inner():
print("Hello", name)
return inner
x = outer("Koti")
x()
Hello Koti
outer() has already completed, inner() remembers name = "Koti".Decorators heavily use closures.
First Decorator without @
def decorator_function(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
def greet():
print("Good morning")
greet = decorator_function(greet)
greet()
Before function execution Good morning After function execution
greet → decorator_function(greet) → wrapper → wrapper executes → before → greet() → after
Using the @ Decorator Syntax
@decorator_function is equivalent to greet = decorator_function(greet)
@decorator_function
def greet():
print("Good morning")
greet()
Before function execution Good morning After function execution
Simple Real-life Example
Imagine a cinema ticket checker. Before entering the movie, someone checks whether you have a ticket.
def ticket_check(func):
def wrapper():
print("checking ticket....")
func()
return wrapper
@ticket_check
def watch_movie():
print("Enjoy the movie")
watch_movie()
checking ticket.... Enjoy the movie
Decorator with Function Arguments
def my_decorator(func):
def wrapper(name):
print("Before function")
func(name)
print("After function")
return wrapper
@my_decorator
def greet(name):
print("Hello", name)
greet("Narayan")
Before function Hello Narayan After function
Universal Decorator with *args and **kwargs
Different functions can have different numbers of arguments. We solve this with *args and **kwargs.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function")
result = func(*args, **kwargs)
print("After function")
return result
return wrapper
@my_decorator
def add(a, b):
return a + b
result = add(10, 30)
print(result)
Before function After function 40
Logging Decorator
Imagine you have many banking functions and you want to log every function execution.
def log_activity(func):
def wrapper(*args, **kwargs):
print(f"{func.__name__} started")
result = func(*args, **kwargs)
print(f"{func.__name__} completed")
return result
return wrapper
@log_activity
def transfer(amount):
print(f"Transferring ${amount}")
transfer(5000)
transfer started Transferring $5000 transfer completed
Authentication Decorator
Suppose only logged-in users can access a bank dashboard.
logged_in = True
def login_required(func):
def wrapper(*args, **kwargs):
if logged_in:
return func(*args, **kwargs)
else:
print("please login first")
return wrapper
@login_required
def dashboard():
print("Welcome to your banking dashboard")
dashboard()
Welcome to your banking dashboard
logged_in = False, the original function will not run and the user will see the message “please login first”.
Python Decorators
Add extra functionality to functions without changing their original code.
Select any topic from the left sidebar to begin.
Start Learning →
