What is a decorator, and how do you implement one in Python?
A decorator is a design pattern in Python that allows you to modify or enhance the behavior of a function or method without changing its source code. Decorators are implemented as higher-order functions that take a function as input and return a new function with the modified behavior.
To implement a decorator in Python, you can define a function that accepts another function as an argument, then create a nested function that wraps the original function. You can add the desired modifications or enhancements within the nested function. Finally, return the nested function from the decorator function.
Here’s an example of a simple decorator that measures the time it takes to execute a given function:
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"{func.__name__} took {elapsed_time:.2f} seconds to execute.")
return result
return wrapper
# Example usage:
@timing_decorator
def some_function(n):
total = 0
for i in range(n):
total += i
return total
result = some_function(10000000)
In this example, we define a decorator called timing_decorator
, which measures the time it takes to execute the given function func
. We use the @timing_decorator
syntax to apply the decorator to some_function
. When some_function(100000)
is called, it prints the time taken to execute the function and returns the result.