ClawSkills logoClawSkills

Python Coding Guidelines

Python 编码指南和最佳实践。用于编写、审查或重构 Python 代码。强制执行 PEP 8 样式,通过 py_compile 进行语法验证、

介绍

# Python Coding Guidelines

## 代码风格 (PEP 8)

- 缩进使用 4 个空格(绝不使用制表符) - 最大行长度:88 字符(Black 默认值)或 79(严格 PEP 8) - 顶级定义前空两行,类内定义前空一行 - 导入顺序:标准库 → 第三方 → 本地,组内按字母排序 - 函数/变量使用 snake_case,类使用 PascalCase,常量使用 UPPER_CASE

## 提交前

```bash # Syntax check (always) python -m py_compile *.py

# Run tests if present python -m pytest tests/ -v 2>/dev/null || python -m unittest discover -v 2>/dev/null || echo "No tests found"

# Format check (if available) ruff check . --fix 2>/dev/null || python -m black --check . 2>/dev/null ```

## Python 版本

- **最低要求:** Python 3.10+(3.9 将于 2025 年 10 月停止维护) - **目标:** 新项目使用 Python 3.11-3.13 - 绝不使用 Python 2 的语法或模式 - 使用现代特性:match 语句、海象运算符、类型提示

## 依赖管理

首先检查 uv,回退到 pip: ```bash # Prefer uv if available if command -v uv &>/dev/null; then uv pip install <package> uv pip compile requirements.in -o requirements.txt else pip install <package> fi ```

使用 uv 的新项目:`uv init` 或 `uv venv && source .venv/bin/activate`

## Pythonic 惯用模式

```python # ✅ List/dict comprehensions over loops squares = [x**2 for x in range(10)] lookup = {item.id: item for item in items}

# ✅ Context managers for resources with open("file.txt") as f: data = f.read()

# ✅ Unpacking first, *rest = items a, b = b, a # swap

# ✅ EAFP over LBYL try: value = d[key] except KeyError: value = default

# ✅ f-strings for formatting msg = f"Hello {name}, you have {count} items"

# ✅ Type hints def process(items: list[str]) -> dict[str, int]: ...

# ✅ dataclasses/attrs for data containers from dataclasses import dataclass

@dataclass class User: name: str email: str active: bool = True

# ✅ pathlib over os.path from pathlib import Path config = Path.home() / ".config" / "app.json"

# ✅ enumerate, zip, itertools for i, item in enumerate(items): ... for a, b in zip(list1, list2, strict=True): ... ```

## 避免的反模式

```python # ❌ Mutable default arguments def bad(items=[]): # Bug: shared across calls ... def good(items=None): items = items or []

# ❌ Bare except try: ... except: # Catches SystemExit, KeyboardInterrupt ... except Exception: # Better ...

# ❌ Global state # ❌ from module import * # ❌ String concatenation in loops (use join) # ❌ == None (use `is None`) # ❌ len(x) == 0 (use `not x`) ```

## 测试

- 使用 pytest(推荐)或 unittest - 测试文件命名为 `test_*.py`,测试函数命名为 `test_*` - 力求专注的单元测试,模拟外部依赖 - 每次提交前运行:`python -m pytest -v`

## 文档字符串 (Docstrings)

```python def fetch_user(user_id: int, include_deleted: bool = False) -> User | None: """Fetch a user by ID from the database. Args: user_id: The unique user identifier. include_deleted: If True, include soft-deleted users. Returns: User object if found, None otherwise. Raises: DatabaseError: If connection fails. """ ```

## 快速检查清单

- [ ] 语法有效 (`py_compile`) - [ ] 测试通过 (`pytest`) - [ ] 公共函数包含类型提示 - [ ] 无硬编码的密钥 - [ ] 使用 f-strings,而非 `.format()` 或 `%` - [ ] 文件路径使用 `pathlib` - [ ] I/O 操作使用上下文管理器 - [ ] 无可变的默认参数

更多产品