Python Decorators
4 min read ·
A decorator is a function that modifies the behavior of another function without changing its source code.
In simple words:
Decorators wrap a function and add extra functionality before or after it runs.
Decorators are heavily used in:
- Logging
- Authentication
- Performance monitoring
- Access control
- Frameworks (Flask, Django)
Functions are First-Class Objects
In Python, functions can be:
- Assigned to variables
- Passed as arguments
- Returned from other functions
Function Inside a Function
This concept is the foundation of decorators.
Returning a Function
Basic Decorator Structure
func→ original functionwrapper→ adds extra behavior
Simple Decorator Example
Using the decorator:
Decorator Without @ Syntax
Decorator with Arguments
Example: Decorator for Logging
Authentication Decorator
Problem
Allow function execution only if user is logged in.
Execution Time Decorator
Problem
Measure how long a function takes to execute.
Retry Decorator
Problem
Retry a function 3 times if it fails.
Input Validation Decorator
Problem
Allow function execution only if input is positive.
Role-Based Access Control
Problem
Only allow admin users to access a function.
Stacking Multiple Decorators
Common Mistakes with Decorators
Forgetting *args, **kwargs ❌
Fails for functions with parameters.
Not Returning Function Result ❌
Caution
Always return the result if the original function returns something.
Real World Example
Real World Scenario
API request logging using decorator
Exercise
Practice Task
- Create a decorator to check password before function call
- Write a decorator to count function calls
- Create a decorator to convert output to uppercase
- Implement retry decorator with custom retry count
- Stack two decorators and observe execution order