125. Decorators with Arguments
Here are 10 Python code snippets demonstrating how to create and use decorators that accept arguments for customization:
1. Basic Decorator with Arguments
def greet(message):
def decorator(func):
def wrapper(*args, **kwargs):
print(message)
return func(*args, **kwargs)
return wrapper
return decorator
@greet("Hello, World!")
def say_name(name):
print(f"My name is {name}")
say_name("John") # Output: Hello, World! My name is John2. Decorator with Arguments for Logging
def log_function_calls(log_message):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"{log_message} - Calling function: {func.__name__}")
result = func(*args, **kwargs)
print(f"{log_message} - Function {func.__name__} completed")
return result
return wrapper
return decorator
@log_function_calls("LOG")
def add(x, y):
return x + y
add(2, 3)3. Decorator with Arguments for Timing
4. Decorator with Arguments for Authorization
5. Decorator for Repeating Function Execution
6. Decorator with Arguments for Caching
7. Decorator with Arguments for Retry Logic
8. Decorator with Arguments for Method Timing
9. Decorator with Arguments for Changing Function Behavior
10. Decorator with Arguments for Conditional Execution
These examples demonstrate how to create and use decorators that accept arguments, allowing for flexible customization of behavior such as logging, timing, caching, retries, and more. Decorators are a powerful tool in Python for enhancing and modifying function behavior dynamically.
Last updated