$npx -y skills add virgo777/buddyme --skill python-patterns构建健壮、高效且易于维护的 Python 应用程序的 Python 惯用法(Pythonic idioms)、PEP 8 标准、类型提示(Type hints)以及最佳实践。
| 1 | # Python 开发模式 (Python Development Patterns) |
| 2 | |
| 3 | 用于构建健壮、高效且易于维护的应用程序的 Python 惯用模式与最佳实践。 |
| 4 | |
| 5 | ## 何时激活 |
| 6 | |
| 7 | - 编写新的 Python 代码时 |
| 8 | - 评审 Python 代码时 |
| 9 | - 重构现有的 Python 代码时 |
| 10 | - 设计 Python 包(Packages)或模块(Modules)时 |
| 11 | |
| 12 | ## 核心原则 |
| 13 | |
| 14 | ### 1. 可读性至上 (Readability Counts) |
| 15 | |
| 16 | Python 优先考虑可读性。代码应当直观且易于理解。 |
| 17 | |
| 18 | ```python |
| 19 | # 推荐:清晰且可读 |
| 20 | def get_active_users(users: list[User]) -> list[User]: |
| 21 | """仅从提供的列表中返回活跃用户。""" |
| 22 | return [user for user in users if user.is_active] |
| 23 | |
| 24 | |
| 25 | # 不推荐:虽然精简但令人困惑 |
| 26 | def get_active_users(u): |
| 27 | return [x for x in u if x.a] |
| 28 | ``` |
| 29 | |
| 30 | ### 2. 显式优于隐式 (Explicit is Better Than Implicit) |
| 31 | |
| 32 | 避免使用“魔法”;确保代码的行为清晰透明。 |
| 33 | |
| 34 | ```python |
| 35 | # 推荐:显式配置 |
| 36 | import logging |
| 37 | |
| 38 | logging.basicConfig( |
| 39 | level=logging.INFO, |
| 40 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
| 41 | ) |
| 42 | |
| 43 | # 不推荐:隐藏的副作用 |
| 44 | import some_module |
| 45 | some_module.setup() # 这行代码具体做了什么? |
| 46 | ``` |
| 47 | |
| 48 | ### 3. EAFP - 宽恕好过许可 (Easier to Ask Forgiveness Than Permission) |
| 49 | |
| 50 | Python 倾向于使用异常处理而非预先检查条件。 |
| 51 | |
| 52 | ```python |
| 53 | # 推荐:EAFP 风格 |
| 54 | def get_value(dictionary: dict, key: str) -> Any: |
| 55 | try: |
| 56 | return dictionary[key] |
| 57 | except KeyError: |
| 58 | return default_value |
| 59 | |
| 60 | # 不推荐:LBYL (Look Before You Leap) 风格 |
| 61 | def get_value(dictionary: dict, key: str) -> Any: |
| 62 | if key in dictionary: |
| 63 | return dictionary[key] |
| 64 | else: |
| 65 | return default_value |
| 66 | ``` |
| 67 | |
| 68 | ## 类型提示 (Type Hints) |
| 69 | |
| 70 | ### 基础类型标注 |
| 71 | |
| 72 | ```python |
| 73 | from typing import Optional, List, Dict, Any |
| 74 | |
| 75 | def process_user( |
| 76 | user_id: str, |
| 77 | data: Dict[str, Any], |
| 78 | active: bool = True |
| 79 | ) -> Optional[User]: |
| 80 | """处理用户并返回更新后的 User 对象或 None。""" |
| 81 | if not active: |
| 82 | return None |
| 83 | return User(user_id, data) |
| 84 | ``` |
| 85 | |
| 86 | ### 现代类型提示 (Python 3.9+) |
| 87 | |
| 88 | ```python |
| 89 | # Python 3.9+ - 使用内置类型 |
| 90 | def process_items(items: list[str]) -> dict[str, int]: |
| 91 | return {item: len(item) for item in items} |
| 92 | |
| 93 | # Python 3.8 及更早版本 - 使用 typing 模块 |
| 94 | from typing import List, Dict |
| 95 | |
| 96 | def process_items(items: List[str]) -> Dict[str, int]: |
| 97 | return {item: len(item) for item in items} |
| 98 | ``` |
| 99 | |
| 100 | ### 类型别名与 TypeVar |
| 101 | |
| 102 | ```python |
| 103 | from typing import TypeVar, Union |
| 104 | |
| 105 | # 复杂类型的类型别名 |
| 106 | JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None] |
| 107 | |
| 108 | def parse_json(data: str) -> JSON: |
| 109 | return json.loads(data) |
| 110 | |
| 111 | # 泛型类型 |
| 112 | T = TypeVar('T') |
| 113 | |
| 114 | def first(items: list[T]) -> T | None: |
| 115 | """返回第一项,如果列表为空则返回 None。""" |
| 116 | return items[0] if items else None |
| 117 | ``` |
| 118 | |
| 119 | ### 基于协议 (Protocol) 的鸭子类型 |
| 120 | |
| 121 | ```python |
| 122 | from typing import Protocol |
| 123 | |
| 124 | class Renderable(Protocol): |
| 125 | def render(self) -> str: |
| 126 | """将对象渲染为字符串。""" |
| 127 | |
| 128 | def render_all(items: list[Renderable]) -> str: |
| 129 | """渲染所有实现了 Renderable 协议的项。""" |
| 130 | return "\n".join(item.render() for item in items) |
| 131 | ``` |
| 132 | |
| 133 | ## 错误处理模式 |
| 134 | |
| 135 | ### 特定的异常处理 |
| 136 | |
| 137 | ```python |
| 138 | # 推荐:捕获特定的异常 |
| 139 | def load_config(path: str) -> Config: |
| 140 | try: |
| 141 | with open(path) as f: |
| 142 | return Config.from_json(f.read()) |
| 143 | except FileNotFoundError as e: |
| 144 | raise ConfigError(f"未找到配置文件: {path}") from e |
| 145 | except json.JSONDecodeError as e: |
| 146 | raise ConfigError(f"配置文件中的 JSON 无效: {path}") from e |
| 147 | |
| 148 | # 不推荐:空 except |
| 149 | def load_config(path: str) -> Config: |
| 150 | try: |
| 151 | with open(path) as f: |
| 152 | return Config.from_json(f.read()) |
| 153 | except: |
| 154 | return None # 静默失败! |
| 155 | ``` |
| 156 | |
| 157 | ### 异常链 (Exception Chaining) |
| 158 | |
| 159 | ```python |
| 160 | def process_data(data: str) -> Result: |
| 161 | try: |
| 162 | parsed = json.loads(data) |
| 163 | except json.JSONDecodeError as e: |
| 164 | # 链接异常以保留回溯信息 |
| 165 | raise ValueError(f"无法解析数据: {data}") from e |
| 166 | ``` |
| 167 | |
| 168 | ### 自定义异常层级 |
| 169 | |
| 170 | ```python |
| 171 | class AppError(Exception): |
| 172 | """所有应用程序错误的基类。""" |
| 173 | pass |
| 174 | |
| 175 | class ValidationError(AppError): |
| 176 | """当输入验证失败时抛出。""" |
| 177 | pass |
| 178 | |
| 179 | class NotFoundError(AppError): |
| 180 | """当请求的资源未找到时抛出。""" |
| 181 | pass |
| 182 | |
| 183 | # 用法 |
| 184 | def get_user(user_id: str) -> User: |
| 185 | user = db.find_user(user_id) |
| 186 | if not user: |
| 187 | raise NotFoundError(f"未找到用户: {user_id}") |
| 188 | return user |
| 189 | ``` |
| 190 | |
| 191 | ## 上下文管理器 (Context Managers) |
| 192 | |
| 193 | ### 资源管理 |
| 194 | |
| 195 | ```python |
| 196 | # 推荐:使用上下文管理器 |
| 197 | def process_file(path: str) -> str: |
| 198 | with open(path, 'r') as f: |
| 199 | return f.read() |
| 200 | |
| 201 | # 不推荐:手动资源管理 |
| 202 | def process_file(path: str) -> str: |
| 203 | f = open(path, 'r') |
| 204 | try: |
| 205 | return f.read() |
| 206 | finally: |
| 207 | f.close() |
| 208 | ``` |
| 209 | |
| 210 | ### 自定义上下文管理器 |
| 211 | |
| 212 | ```python |
| 213 | from contextlib import contextmanager |
| 214 | |
| 215 | @contextmanager |
| 216 | def timer(name: str): |
| 217 | """计时代码块的上下文管理器。""" |
| 218 | start = time.perf_counter() |
| 219 | yield |
| 220 | elapsed = time.perf_counter() - start |
| 221 | print(f"{name} 耗时 {elapsed:.4f} 秒") |
| 222 | |
| 223 | # 用法 |
| 224 | with timer("数据处理"): |
| 225 | process_large_dataset() |
| 226 | ``` |
| 227 | |
| 228 | ### 上下文管理器类 |
| 229 | |
| 230 | ```python |
| 231 | class DatabaseTransaction: |
| 232 | def __init__(self, connection): |
| 233 | self.connection = connection |
| 234 | |
| 235 | def __enter__(self): |
| 236 | self.connection.begin_transaction() |
| 237 | return self |
| 238 | |
| 239 | def __exit__(self, exc_type, exc_val, exc_tb): |
| 240 | if exc_type is None: |
| 241 | self.connection.commit() |
| 242 | else: |
| 243 | self.connection.rollback() |
| 244 | return False # 不要抑制异常 |
| 245 | |
| 246 | # 用法 |
| 247 | with DatabaseTransaction(conn): |
| 248 | user = conn.create_user(user_data) |
| 249 | conn.create_profile(user.id, profile_data) |
| 250 | ``` |
| 251 | |
| 252 | ## 推导式 (Comprehensions) 与生成器 (Gen |