
Introduction to Python Decorators
Python decorators are a way to modify or extend the behavior of functions or methods without altering their actual code. They enable developers to add functionality to an existing function in a flexible and reusable way. In simple terms, a decorator is a function that wraps another function, adding new capabilities to it.
Basic Syntax of a Decorator
In Python, decorators are defined with the @decorator_name
syntax above the function you want to modify. Here’s a simple example:
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()
In this example, my_decorator
takes say_hello
as an argument, wrapping it in additional functionality. When say_hello()
is called, the decorator executes code before and after the main function.
Using Decorators with Arguments
Decorators can also work with functions that accept arguments. Here’s how to modify a decorator to accept any number of arguments:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Function is about to be called with arguments:", args, kwargs)
result = func(*args, **kwargs)
print("Function has been called.")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Here, we use *args
and **kwargs
to make the decorator compatible with any number of arguments, allowing greet
to pass parameters as expected.
Practical Applications of Decorators
Decorators are commonly used for:
- Logging function calls and arguments
- Enforcing access control
- Caching function results for efficiency
- Timing code execution
Below is an example of a timer decorator that logs how long a function takes to run:
import time
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Execution time: {end_time - start_time:.4f} seconds")
return result
return wrapper
@timer
def calculate_sum(limit):
return sum(range(limit))
calculate_sum(1000000)
With the timer
decorator, we can quickly measure the performance of calculate_sum
without modifying its original code.
Conclusion
Decorators are a powerful tool in Python, promoting cleaner and more modular code. By mastering decorators, you can enhance code reusability and maintainability, making your functions more versatile. Try experimenting with decorators to see how they can improve your coding practices.
0 Comments