A Decorator is a function that modifies or extends the behavior of another function without changing its original code.
Decorators are commonly used for logging, authentication, validation, and performance monitoring.
Basic Function Example
Example
def greet():
print("Hello")
greet()
Output:
Hello
Creating a Decorator
Example
def my_decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
def greet():
print("Hello")
greet = my_decorator(greet)
greet()
Output:
Before Function
Hello
After Function
Using @ Decorator Syntax
Python provides the @ symbol as a shortcut for applying decorators.
Example
def my_decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
@my_decorator
def greet():
print("Hello")
greet()
Output:
Before Function
Hello
After Function
Decorator with Arguments
Example
def my_decorator(func):
def wrapper(name):
print("Welcome")
func(name)
return wrapper
@my_decorator
def greet(name):
print("Hello", name)
greet("John")
Output:
Welcome
Hello John
Returning Values from Decorators
Example
def my_decorator(func):
def wrapper():
return func() * 2
return wrapper
@my_decorator
def get_number():
return 10
print(get_number())
Output:
20
Multiple Decorators
Example
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 greet():
print("Hello")
greet()
Output:
Decorator 1
Decorator 2
Hello
Real-World Example
Example
def login_required(func):
def wrapper():
print("Checking Login...")
func()
return wrapper
@login_required
def dashboard():
print("Dashboard Opened")
dashboard()
Output:
Checking Login...
Dashboard Opened
Summary
- Decorators modify the behavior of functions.
- A decorator is a function that accepts another function.
- The
@syntax is used to apply decorators. - Decorators help avoid code duplication.
- They are commonly used for logging, authentication, caching, and validation.
- Multiple decorators can be applied to a single function.