- Learning Objectives
- Prerequisites
- Introduction
- What is a Decorator?
- Why are Decorators Required?
- Real-World Analogy
- How Decorators Work
- Syntax of Decorators
- Components of a Decorator
- Nested Functions
- Wrapper Functions
- @ Symbol
- Multiple Decorators
- Advantages
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand decorators.
- Understand higher-order functions.
- Create custom decorators.
- Use wrapper functions.
- Use the @ syntax.
- Create multiple decorators.
- Apply decorators in real-world applications.
Before learning this chapter, you should know:
- Functions
- Lambda Functions
- Nested Functions
- Returning Functions
- Functional Programming Basics
In software development,
developers often need to perform some common tasks before or after executing a function.
Examples include:
- Logging
- Authentication
- Authorization
- Performance measurement
- Input validation
- Exception handling
Writing the same code repeatedly inside every function leads to duplicate code.
Python solves this problem using Decorators.
A Decorator is a function that receives another function as an argument, adds additional functionality, and returns a new function without modifying the original function.
A decorator adds extra functionality to an existing function without changing its original code.
Suppose you have 100 functions.
Each function must:
- Log execution
- Check authentication
- Measure execution time
Without decorators,
the same code must be written 100 times.
Decorators allow writing that logic once and applying it wherever needed.
Imagine a birthday gift.
Original Item
Book
Decorator
Gift Wrapper
Final Product
Gift Wrapped Book
The book remains the same.
Only additional decoration is added.
Similarly,
a decorator keeps the original function unchanged while adding extra behavior.
A higher-order function is a function that:
- Accepts another function as an argument.
- Returns another function.
Decorators are built using higher-order functions.
Example
def display():
print("Hello")A decorator receives
displayas an argument.
Original Function
↓
Decorator
↓
Wrapper Function
↓
Additional Functionality
↓
Original Function Executes
↓
Additional Functionality
↓
Output
Without @ Symbol
def decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapperApplying Decorator
decorated = decorator(display)
decorated()Using @ Symbol
@decorator
def display():
print("Hello")Python automatically executes
display = decorator(display)A decorator consists of three functions.
def display():
print("Hello")def decorator(func):Receives another function.
def wrapper():Executes
- Before logic
- Original function
- After logic
A function defined inside another function is called a nested function.
Example
def outer():
def inner():
print("Inner Function")
inner()Nested functions are the foundation of decorators.
The wrapper function controls the execution of the original function.
Example
Wrapper
↓
Before Code
↓
Original Function
↓
After Code
Python provides
@for applying decorators.
Instead of writing
display = decorator(display)we simply write
@decoratorThis makes the code cleaner and easier to read.
A function can have multiple decorators.
Example
@decorator1
@decorator2
def display():
passExecution Order
decorator1
↓
decorator2
↓
Original Function
Decorators are commonly used for:
- Authentication
- Authorization
- Logging
- Performance Measurement
- Caching
- Retry Mechanisms
- Validation
- Exception Handling
- API Development
- Web Frameworks
- Promotes code reuse.
- Eliminates duplicate code.
- Improves readability.
- Keeps business logic clean.
- Easy maintenance.
- Widely used in professional projects.
- Keep decorators focused on one responsibility.
- Use meaningful decorator names.
- Keep wrapper functions simple.
- Preserve function metadata using
functools.wraps. - Avoid excessive nesting of decorators.
Forgetting to return the wrapper function.
Incorrect
returnCorrect
return wrapperCalling the function instead of passing it.
Incorrect
decorator(display())Correct
decorator(display)Not accepting arguments in the wrapper when decorating functions that require parameters.
Creating overly complex decorators.
Function Created
↓
Decorator Receives Function
↓
Wrapper Created
↓
Wrapper Returned
↓
Function Replaced
↓
Function Called
↓
Wrapper Executes
↓
Before Logic
↓
Original Function
↓
After Logic
↓
Output
A decorator is a function that adds additional functionality to another function without modifying its original code.
To add reusable functionality such as logging, authentication, validation, and timing without duplicating code.
A function that accepts another function as an argument or returns another function.
A nested function inside the decorator that executes additional code before and/or after the original function.
@Yes.
Multiple decorators can be stacked above a function.
No.
They extend its behavior without changing its source code.
- Decorator → Adds functionality.
- Higher-Order Function.
- Wrapper Function.
- Nested Function.
- Uses
@. - Promotes code reuse.
- Common in professional Python projects.
In this chapter, you learned:
- Decorators
- Higher-Order Functions
- Nested Functions
- Wrapper Functions
- @ Symbol
- Multiple Decorators
- Advantages
- Best Practices
- Common Mistakes
- Interview Questions
- Quick Revision
Write a Python program to create a basic decorator without using the @ symbol.
def decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
def display():
print("Hello Python")
decorated = decorator(display)
decorated()Before Function
Hello Python
After Function
The decorator receives the display() function.
The wrapper executes code before and after the original function.
def decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
@decorator
def display():
print("Learning Decorators")
display()Before Function
Learning Decorators
After Function
The @decorator syntax is equivalent to:
display = decorator(display)def decorator(func):
def wrapper(a, b):
print("Addition Started")
func(a, b)
print("Addition Completed")
return wrapper
@decorator
def add(a, b):
print("Result :", a + b)
add(10, 20)Addition Started
Result : 30
Addition Completed
The wrapper accepts the same arguments as the original function.
def decorator(func):
def wrapper(a, b):
print("Calculating...")
return func(a, b)
return wrapper
@decorator
def multiply(a, b):
return a * b
print(multiply(5, 6))Calculating...
30
The wrapper returns the value produced by the original function.
def logger(func):
def wrapper():
print("Function Execution Started")
func()
print("Function Execution Finished")
return wrapper
@logger
def task():
print("Processing Data")
task()Function Execution Started
Processing Data
Function Execution Finished
Logging decorators are commonly used to track function execution.
def authenticate(func):
def wrapper(user):
if user == "admin":
func(user)
else:
print("Access Denied")
return wrapper
@authenticate
def dashboard(user):
print("Welcome", user)
dashboard("admin")
dashboard("guest")Welcome admin
Access Denied
The decorator checks authentication before executing the function.
import time
def timer(func):
def wrapper():
start = time.time()
func()
end = time.time()
print("Execution Time :", end - start)
return wrapper
@timer
def task():
time.sleep(2)
task()Execution Time : 2.00...
The decorator measures how long a function takes to execute.
def decorator1(func):
def wrapper():
print("Decorator 1")
func()
return wrapper
def decorator2(func):
def wrapper():
print("Decorator 2")
func()
return wrapper
@decorator1
@decorator2
def display():
print("Original Function")
display()Decorator 1
Decorator 2
Original Function
Decorators execute from the top down.
The innermost decorator calls the original function.
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper():
print("Before")
func()
return wrapper
@decorator
def display():
"""Display Function"""
print("Hello")
print(display.__name__)
print(display.__doc__)display
Display Function
functools.wraps preserves the metadata of the original function, such as its name and documentation string.
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Function Started")
result = func(*args, **kwargs)
print("Function Finished")
return result
return wrapper
@logger
def square(number):
return number * number
print(square(6))Function Started
Function Finished
36
*args and **kwargs allow the decorator to work with functions that accept any number of positional and keyword arguments.
Function Defined
↓
Decorator Applied
↓
Wrapper Created
↓
Function Replaced
↓
Function Called
↓
Wrapper Executes
↓
Before Code
↓
Original Function
↓
After Code
↓
Result Returned
Memory
│
├── Original Function
│
├── Decorator
│
└── Wrapper Function
│
├── Before Logic
├── Original Function
└── After Logic
- Promotes code reuse.
- Reduces duplicate code.
- Separates business logic from common tasks.
- Improves readability.
- Simplifies maintenance.
- Widely used in Python frameworks.
- Use
functools.wrapsto preserve function metadata. - Keep decorators focused on one responsibility.
- Use
*argsand**kwargsfor reusable decorators. - Keep wrapper functions simple.
- Write meaningful decorator names.
Forgetting to return the wrapper.
Calling the function instead of passing it.
Incorrect
decorator(display())Correct
decorator(display)Not returning the original function's result.
Ignoring *args and **kwargs.
This limits the decorator to functions with fixed parameters.
A decorator is a function that extends the behavior of another function without modifying its original code.
To add reusable functionality such as logging, authentication, caching, validation, and performance measurement.
@A nested function inside the decorator that executes additional code before and/or after the original function.
It preserves the original function's metadata, such as its name and documentation string.
Yes.
Multiple decorators can be stacked on a single function.
They allow decorators to work with functions that accept different numbers and types of arguments.
No.
They extend its behavior while leaving the original implementation unchanged.
- Create a decorator that prints messages before and after a function.
- Create a logging decorator.
- Create an authentication decorator.
- Create a timing decorator.
- Create a decorator using
functools.wraps. - Apply multiple decorators to a function.
- Create a decorator that accepts functions with different arguments.
- Decorator → Adds functionality.
- Uses
@. - Wrapper Function.
- Higher-Order Function.
- Nested Function.
functools.wraps*args**kwargs- Multiple Decorators.
- Promotes code reuse.
In this chapter, you learned:
- Decorators
- Higher-Order Functions
- Nested Functions
- Wrapper Functions
- @ Symbol
- Decorators with Arguments
- Returning Values
- Logging Decorators
- Authentication Decorators
- Timing Decorators
- Multiple Decorators
- functools.wraps
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision