Return Value Handling
Understanding Return Value Modification
Decorators can intercept, modify, and transform return values from functions, providing powerful ways to manipulate function outputs.
Basic Return Value Passing
def result_multiplier(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * 2
return wrapper
@result_multiplier
def calculate(x, y):
return x + y
print(calculate(3, 4)) ## Output: 14
Conditional Return Handling
def validate_result(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result if result > 0 else None
return wrapper
@validate_result
def divide(a, b):
return a / b
print(divide(10, 2)) ## Output: 5.0
print(divide(5, -2)) ## Output: None
def convert_to_list(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return [result] if not isinstance(result, list) else result
return wrapper
@convert_to_list
def get_data():
return "Single Item"
print(get_data()) ## Output: ['Single Item']
Decorator Return Value Workflow
graph TD
A[Original Function] --> B[Decorator Wrapper]
B --> C[Function Execution]
C --> D{Modify Return?}
D -->|Yes| E[Transform Result]
D -->|No| F[Pass Original Result]
E --> G[Return Modified Result]
F --> G
Return Value Handling Strategies
Strategy |
Description |
Use Case |
Passthrough |
Directly return original result |
Simple scenarios |
Transformation |
Modify return value |
Data preprocessing |
Validation |
Filter or validate results |
Error handling |
Caching |
Store and return cached results |
Performance optimization |
Advanced Return Handling Example
def retry_on_failure(max_attempts=3):
def decorator(func):
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
result = func(*args, **kwargs)
return result
except Exception as e:
attempts += 1
if attempts == max_attempts:
raise e
return wrapper
return decorator
@retry_on_failure(max_attempts=3)
def unstable_network_call():
## Simulated network operation
import random
if random.random() < 0.7:
raise ConnectionError("Network unstable")
return "Success"
Key Considerations
- Preserve function metadata using
functools.wraps
- Handle different return types gracefully
- Consider performance implications
LabEx recommends practicing these patterns to master decorator return value handling techniques.