Applying Parameterized Decorators
Now that you understand how to create parameterized decorators, let's explore some practical applications and examples.
Logging with Parameterized Decorators
One common use case for parameterized decorators is adding logging functionality to your functions. Here's an example:
def log_function_call(log_level):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"{log_level.upper()}: Calling function {func.__name__}")
return func(*args, **kwargs)
return wrapper
return decorator
@log_function_call("info")
def add_numbers(a, b):
return a + b
print(add_numbers(2, 3)) ## Output: INFO: Calling function add_numbers
## Output: 5
In this example, the log_function_call
decorator takes a log_level
argument, which is used to determine the logging level for the function call.
Caching with Parameterized Decorators
Another common use case for parameterized decorators is adding caching functionality to your functions. Here's an example:
from functools import lru_cache
def cache_results(maxsize=128):
def decorator(func):
@lru_cache(maxsize=maxsize)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator
@cache_results(maxsize=32)
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(100)) ## Output: 354224848179261915075
In this example, the cache_results
decorator takes a maxsize
argument, which determines the maximum size of the cache. The lru_cache
function from the functools
module is used to implement the caching functionality.
Other Use Cases
Parameterized decorators can be used for a wide range of other use cases, such as:
- Authentication and Authorization: Decorators can be used to check if a user has the necessary permissions to access a function or resource.
- Performance Monitoring: Decorators can be used to measure the execution time of a function, or to profile the performance of a function.
- Feature Flags: Decorators can be used to conditionally enable or disable certain features of an application.
By understanding how to apply parameterized decorators, you can write more powerful and flexible Python code that meets a wide range of requirements.