Decorators in Python
1. Introduction
Decorators in Python are a powerful and expressive way to modify the behavior of functions or methods. They allow you to wrap another function in order to extend its behavior without permanently modifying it.
2. What are Decorators?
A decorator is a function that takes another function as an argument, extends its behavior, and returns a new function. This is often used for logging, enforcing access control, instrumentation, and caching.
3. Creating Decorators
To create a decorator, define a function that takes a function as an argument, defines a nested function that modifies the behavior, and returns the nested function.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
4. Decorator Arguments
Sometimes you may want to pass arguments to your decorators. To achieve this, you need to create a decorator that returns another decorator.
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
func(*args, **kwargs)
return wrapper
return decorator_repeat
@repeat(3)
def greet(name):
print(f"Hello {name}")
greet("World")
5. Common Use Cases
- Logging function calls
- Access control and authentication
- Memoization and caching
- Timing function execution
6. Best Practices
Here are some best practices when working with decorators:
- Always use the built-in
functools.wraps
to preserve the original function's metadata. - Keep decorators simple and focused on a single responsibility.
- Document decorators clearly, including their parameters and return values.
- Test decorators independently to ensure they behave as expected.
7. FAQ
What is the difference between a function and a method in Python?
A function is a block of code that is designed to perform a particular task. A method is a function that is associated with an object and can access its data.
Can decorators be applied to classes?
Yes, decorators can also be applied to classes to modify their behavior, similar to how they modify functions.
How do decorators handle arguments?
To handle arguments in decorators, you create a decorator that returns another decorator function, allowing the nested function to accept the arguments.