Decorators with Arguments
Understanding Decorator Arguments
Decorators can accept arguments to provide more flexibility and customization. There are two primary ways to create decorators with arguments:
- Decorators that accept function arguments
- Decorators that accept their own arguments
Decorator Accepting Function Arguments
def validate_args(func):
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, int):
raise TypeError(f"Expected integer, got {type(arg)}")
return func(*args, **kwargs)
return wrapper
@validate_args
def add_numbers(a, b):
return a + b
print(add_numbers(3, 4)) ## Works fine
## print(add_numbers(3, "4")) ## Raises TypeError
Decorator with Custom Arguments
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def greet(name):
print(f"Hello, {name}!")
greet("LabEx")
Decorator Argument Flow
graph TD
A[Decorator Arguments] --> B[Decorator Factory]
B --> C[Decorator Wrapper]
C --> D[Original Function]
D --> E[Return Result]
Types of Decorator Arguments
Argument Type |
Description |
Example |
Positional |
Fixed position arguments |
@repeat(3) |
Keyword |
Named arguments |
@validate(min_length=5) |
Mixed |
Combination of positional and keyword |
@custom_decorator(10, strict=True) |
Advanced Argument Handling
def log_calls(log_level='INFO'):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"[{log_level}] Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
return decorator
@log_calls(log_level='DEBUG')
def complex_calculation(x, y):
return x * y
complex_calculation(5, 6)
Best Practices
- Use nested functions for complex argument processing
- Preserve original function metadata using
functools.wraps
- Keep decorator logic clean and focused
- Handle different argument scenarios gracefully
By mastering decorators with arguments, you'll unlock powerful metaprogramming techniques in Python, enhancing your code's flexibility and reusability in LabEx programming projects.