Decorators in Python allow you to modify or extend the behavior of functions or methods. They are often used to add functionality to existing code in a reusable and readable way.
Decorators in Python
1. What is a Decorator?
A decorator is a function that takes another function as an argument, adds some functionality to it, and returns a new function. Decorators are typically used to wrap a function, altering its behavior without changing its actual code.
2. Creating a Basic Decorator
Let's look at a simple decorator that prints a message before and after the function it wraps:
def my_decorator(func):
def wrapper():
print("Something is about to happen!")
func()
print("Something has just happened!")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Something is about to happen!
# Hello!
# Something has just happened!
In this example, @my_decorator
applies my_decorator
to say_hello
, modifying its behavior without changing its code directly.
3. Using Decorators with Arguments
Decorators can also modify functions that take arguments. Here’s how:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Output:
# Before the function call
# Hello, Alice!
# After the function call
The *args
and **kwargs
allow the decorator to handle functions with any number of arguments.
4. Practical Uses for Decorators
Decorators are commonly used for:
- Logging: Automatically log the calls to a function.
- Access Control: Restrict access based on user roles.
- Caching: Cache results of expensive computations.
- Timing: Measure the time a function takes to run.
5. Chaining Multiple Decorators
In Python, you can apply multiple decorators to a single function. They are applied in a bottom-up order:
def uppercase(func):
def wrapper():
result = func()
return result.upper()
return wrapper
def make_bold(func):
def wrapper():
result = func()
return f"<b>{result}</b>"
return wrapper
@make_bold
@uppercase
def greet():
return "Hello"
print(greet())
# Output:
# <b>HELLO</b>
In this example, uppercase
is applied first, then make_bold
.
6. Summary
Decorators in Python provide a powerful and flexible way to modify the behavior of functions and methods. By using decorators, you can apply cross-cutting concerns such as logging, access control, or timing in a reusable manner.