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
Copy
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
Copy
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
Copy
4. Decorator with Arguments for Authorization
Copy
5. Decorator for Repeating Function Execution
Copy
6. Decorator with Arguments for Caching
Copy
7. Decorator with Arguments for Retry Logic
Copy
8. Decorator with Arguments for Method Timing
Copy
9. Decorator with Arguments for Changing Function Behavior
Copy
10. Decorator with Arguments for Conditional Execution
Copy
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