Advanced Default Strategies
Dynamic Default Values
Using Functions for Default Arguments
from datetime import datetime
def log_event(event, timestamp=None):
if timestamp is None:
timestamp = datetime.now()
print(f"Event: {event} at {timestamp}")
## Dynamic default value
log_event("User Login")
Keyword-Only Arguments with Defaults
def advanced_function(required_arg, *,
optional_1=None,
optional_2=True):
"""
Demonstrates keyword-only arguments with defaults
"""
return {
'required': required_arg,
'optional1': optional_1,
'optional2': optional_2
}
## Usage examples
result = advanced_function(10, optional_1="Custom")
Default Argument Strategies
flowchart TD
A[Advanced Defaults] --> B[Dynamic Generation]
A --> C[Conditional Defaults]
A --> D[Type Flexibility]
Conditional Default Generation
def create_user(username,
email=None,
is_admin=False):
if email is None:
email = f"{username}@example.com"
return {
'username': username,
'email': email,
'admin_status': is_admin
}
## Flexible user creation
user1 = create_user("john_doe")
user2 = create_user("admin", email="[email protected]", is_admin=True)
Advanced Pattern Matching
def process_data(data,
transformer=lambda x: x,
validator=lambda x: x is not None):
"""
Flexible data processing with default transformers
"""
processed_data = transformer(data)
if validator(processed_data):
return processed_data
raise ValueError("Invalid processed data")
## Different transformation strategies
result1 = process_data([1, 2, 3])
result2 = process_data([1, 2, 3],
transformer=sum,
validator=lambda x: x > 0)
Default Argument Patterns
Strategy |
Description |
Use Case |
Function Defaults |
Generate values dynamically |
Timestamps, unique IDs |
Conditional Defaults |
Provide smart fallback values |
User configurations |
Type Flexibility |
Support multiple input types |
Generic data processing |
def efficient_defaults(
data,
cache=None,
max_cache_size=100
):
if cache is None:
cache = {}
## Efficient caching mechanism
if len(cache) >= max_cache_size:
cache.clear()
return cache
Best Practices
- Use
None
for mutable default values
- Prefer simple, predictable defaults
- Leverage function-based default generation
- Consider type hints for clarity
At LabEx, we emphasize understanding these advanced default argument strategies to write more flexible and robust Python code.