22. Custom Decorators with Arguments
Custom decorators with arguments allow you to create more flexible and dynamic decorators by passing arguments to the decorator itself.
1. Decorator with a Simple Argument
Copy
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()Output:
Copy
Hello!
Hello!
Hello!2. Logging Decorator with a Custom Message
Copy
Output:
Copy
3. Timing Decorator with a Label
Copy
Output:
Copy
4. Access Control Decorator with a Role
Copy
5. Rate Limiter with a Custom Limit
Copy
6. Dynamic Prefix Decorator
Copy
Output:
Copy
7. Validation Decorator with Custom Error Message
Copy
8. Custom Logger Decorator with Log Levels
Copy
Output:
Copy
9. Retry Decorator with Retry Count
Copy
10. Environment-Specific Execution Decorator
Copy
Last updated