- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Decorator Definition
A decorator in Python is a function that modifies the behavior of another function, without changing its code.
Think of a decorator as adding a layer of functionality before and/or after the original function runs.
Why Use Decorators?
| Purpose | Example Use Case |
|---|---|
| Add functionality without editing original code | Logging, Authorization |
| Reuse common logic | Validation |
| Track performance | Execution time calculator |
| Restrict access | Admin/user roles |
Basic Decorator Structure
def decorator_function(original_function):
def wrapper_function():
# Code before
original_function()
# Code after
return wrapper_function
Applying a Decorator
@decorator_function
def display():
print("Display function executed")
The @decorator_function applies extra behavior to the display() function.
Basic Example
def my_decorator(func):
def wrapper():
print("Before function runs")
func()
print("After function runs")
return wrapper
@my_decorator
def greet():
print("Hello!")
greet()
Output:
Before function runs
Hello!
After function runs
Decorator With Arguments
def decorator(func):
def wrapper(*args, **kwargs):
print("Arguments:", args, kwargs)
return func(*args, **kwargs)
return wrapper
@decorator
def add(a, b):
print("Sum =", a + b)
add(5, 3)
Decorator Returning a Value
def decorator(func):
def wrapper(*args):
result = func(*args)
print("Function returned:", result)
return result
return wrapper
@decorator
def multiply(x, y):
return x * y
multiply(4, 5)
Real-World Example – Logging
def logger(func):
def wrapper(*args, **kwargs):
print(f"Running function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def show():
print("Inside show function")
show()
Example – Execution Time Calculator
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution Time: {end-start:.5f} seconds")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
slow_function()
Authentication / Access Control
def require_admin(func):
def wrapper(user):
if user != "admin":
print("Access Denied!")
else:
return func(user)
return wrapper
@require_admin
def delete_data(user):
print("Data deleted successfully!")
delete_data("guest")
delete_data("admin")
Decorators with Parameters (Advanced)
Sometimes we need the decorator to accept its own argument:
def repeat(num):
def decorator(func):
def wrapper():
for _ in range(num):
func()
return wrapper
return decorator
@repeat(3)
def hello():
print("Hello")
hello()
Output
Hello
Hello
Hello
Nesting Multiple Decorators
def bold(func):
def wrapper():
print("<b>", end="")
func()
print("</b>")
return wrapper
def italic(func):
def wrapper():
print("<i>", end="")
func()
print("</i>")
return wrapper
@bold
@italic
def text():
print("Decorated Text", end="")
text()