Python 开发模式
用于构建健壮、高效和可维护应用程序的惯用 Python 模式与最佳实践。
何时激活
- 编写新的 Python 代码
- 审查 Python 代码
- 重构现有的 Python 代码
- 设计 Python 包/模块
核心原则
1. 可读性很重要
Python 优先考虑可读性。代码应该清晰且易于理解。
# Good: Clear and readable
def get_active_users(users: list[User]) -> list[User]:
"""Return only active users from the provided list."""
return [user for user in users if user.is_active]
# Bad: Clever but confusing
def get_active_users(u):
return [x for x in u if x.a]
2. 显式优于隐式
避免魔法;清晰说明你的代码在做什么。
# Good: Explicit configuration
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Bad: Hidden side effects
import some_module
some_module.setup() # What does this do?
3. EAFP - 请求宽恕比请求许可更容易
Python 倾向于使用异常处理而非检查条件。
# Good: EAFP style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
# Bad: LBYL (Look Before You Leap) style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
if key in dictionary:
return dictionary[…