Advanced Applications
Decorator Integration with Partial Functions
Combining decorators and partial functions creates powerful function transformation techniques:
from functools import partial, wraps
def rate_limit(max_calls):
def decorator(func):
call_count = 0
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count > max_calls:
raise Exception("Rate limit exceeded")
return func(*args, **kwargs)
return wrapper
return decorator
def api_request(endpoint, method, data=None):
return f"Requesting {method} {endpoint} with {data}"
## Create rate-limited API functions
github_api = partial(api_request, endpoint='https://api.github.com')
limited_github_api = rate_limit(3)(github_api)
graph TD
A[Partial Function] --> B[Dynamic Function Generation]
B --> C[Runtime Configuration]
B --> D[Adaptive Behavior]
Advanced Type Handling
from functools import partial
from typing import Callable, Any
def type_validated_function(validator: Callable[[Any], bool], func: Callable):
def wrapper(*args, **kwargs):
if not all(validator(arg) for arg in args):
raise TypeError("Invalid argument type")
return func(*args, **kwargs)
return wrapper
def is_positive(x):
return x > 0
def calculate_power(base, exponent):
return base ** exponent
## Create type-safe partial functions
safe_power = partial(
type_validated_function(is_positive, calculate_power)
)
print(safe_power(2, 3)) ## Works
## print(safe_power(-2, 3)) ## Raises TypeError
Parallel Processing Strategies
Strategy |
Description |
Use Case |
Function Specialization |
Create optimized worker functions |
Distributed computing |
Argument Pre-configuration |
Prepare functions for parallel execution |
Multiprocessing |
Dynamic Dispatch |
Runtime function selection |
Complex workflow management |
Machine Learning Model Configuration
def create_model_trainer(optimizer, learning_rate, loss_function):
def train_model(model, dataset):
return f"Training model with {optimizer}, lr={learning_rate}, loss={loss_function}"
return train_model
## Specialized model training configurations
sgd_trainer = partial(create_model_trainer, optimizer='SGD', learning_rate=0.01)
adam_trainer = partial(create_model_trainer, optimizer='Adam', learning_rate=0.001)
neural_net_trainer = sgd_trainer(loss_function='cross_entropy')
Dependency Injection Patterns
class DatabaseConnection:
def __init__(self, host, port, driver):
self.connection_string = f"{driver}://{host}:{port}"
def create_database_connection(host='localhost', port=5432, driver='postgresql'):
return DatabaseConnection(host, port, driver)
## Partial function for specific database configurations
mysql_connection = partial(create_database_connection, driver='mysql', port=3306)
postgres_connection = partial(create_database_connection, driver='postgresql', port=5432)
LabEx Advanced Development Techniques
Key areas where partial functions enhance development:
- Middleware composition
- Configuration management
- Dynamic service adaptation
- Minimal runtime overhead
- Efficient memory usage
- Recommended for complex, configurable architectures
Error Handling and Validation
def validate_arguments(validator, func):
def wrapper(*args, **kwargs):
if not validator(*args, **kwargs):
raise ValueError("Invalid arguments")
return func(*args, **kwargs)
return wrapper
def range_validator(min_val, max_val):
def validator(x):
return min_val <= x <= max_val
return validator
safe_divide = partial(
validate_arguments(range_validator(1, 100)),
lambda x, y: x / y
)