Best Practices Guide
Designing Safe Default Arguments
1. Use None for Mutable Defaults
def create_collection(name, items=None):
if items is None:
items = []
return {"name": name, "items": items}
Argument Default Strategy
graph TD
A[Default Argument Design] --> B[Immutable Defaults]
A --> C[None for Mutable Objects]
A --> D[Explicit Initialization]
Recommended Practices
Practice |
Description |
Example |
Avoid Mutable Defaults |
Use None instead |
def func(x, lst=None) |
Explicit Initialization |
Create new instances |
lst = lst or [] |
Type Hints |
Improve code readability |
def func(x: int = 0) |
Type Hinting with Default Arguments
from typing import List, Optional
def process_data(
data: Optional[List[int]] = None,
threshold: int = 10
) -> List[int]:
data = data or []
return [x for x in data if x > threshold]
Configuration Patterns
class DatabaseConfig:
def __init__(
self,
host: str = 'localhost',
port: int = 5432,
timeout: Optional[int] = None
):
self.host = host
self.port = port
self.timeout = timeout or 30
Function Overloading Alternatives
def connect(
host: str = 'localhost',
*, ## Force keyword arguments
port: int = 8000,
secure: bool = False
):
connection_string = f"{host}:{port}"
return {
"connection": connection_string,
"secure": secure
}
Error Handling with Defaults
def validate_input(
value: Optional[str] = None,
default: str = "Unknown"
) -> str:
if value is None or value.strip() == "":
return default
return value.strip()
- Minimal overhead for
None
checks
- Readability trumps micro-optimizations
- Use
or
for concise initialization
Advanced Default Argument Techniques
def flexible_logger(
message: str,
level: str = "INFO",
tags: Optional[dict] = None
):
tags = tags or {}
log_entry = {
"message": message,
"level": level,
**tags
}
return log_entry
Key Recommendations
- Always use
None
for mutable defaults
- Create new instances inside functions
- Use type hints for clarity
- Prefer explicit initialization
- Consider keyword-only arguments
LabEx recommends practicing these patterns to write more robust and predictable Python code.