最佳实践指南
设计安全的默认参数
1. 对可变默认值使用 None
def create_collection(name, items=None):
if items is None:
items = []
return {"name": name, "items": items}
参数默认策略
graph TD
A[默认参数设计] --> B[不可变默认值]
A --> C[可变对象使用 None]
A --> D[显式初始化]
推荐实践
实践 |
描述 |
示例 |
避免可变默认值 |
使用 None 代替 |
def func(x, lst=None) |
显式初始化 |
创建新实例 |
lst = lst or [] |
类型提示 |
提高代码可读性 |
def func(x: int = 0) |
带默认参数的类型提示
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]
配置模式
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
函数重载替代方案
def connect(
host: str = 'localhost',
*, ## 强制使用关键字参数
port: int = 8000,
secure: bool = False
):
connection_string = f"{host}:{port}"
return {
"connection": connection_string,
"secure": secure
}
带默认值的错误处理
def validate_input(
value: Optional[str] = None,
default: str = "Unknown"
) -> str:
if value is None or value.strip() == "":
return default
return value.strip()
性能考虑
- None 检查的开销最小
- 可读性优于微优化
- 使用
or
进行简洁初始化
高级默认参数技术
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
关键建议
- 对可变默认值始终使用 None
- 在函数内部创建新实例
- 使用类型提示以提高清晰度
- 优先使用显式初始化
- 考虑使用仅限关键字的参数
LabEx 建议通过实践这些模式来编写更健壮、更具可预测性的 Python 代码。