Python Coding Guidelines
Code Style (PEP 8)
- - 4 spaces for indentation (never tabs)
- Max line length: 88 chars (Black default) or 79 (strict PEP 8)
- Two blank lines before top-level definitions, one within classes
- Imports: stdlib → third-party → local, alphabetized within groups
- Snakecase for functions/variables, PascalCase for classes, UPPERCASE for constants
Before Committing
CODEBLOCK0
Python Version
- - Minimum: Python 3.10+ (3.9 EOL Oct 2025)
- Target: Python 3.11-3.13 for new projects
- Never use Python 2 syntax or patterns
- Use modern features: match statements, walrus operator, type hints
Dependency Management
Check for uv first, fall back to pip:
CODEBLOCK1
For new projects with uv: uv init or INLINECODE1
Pythonic Patterns
CODEBLOCK2
Anti-patterns to Avoid
CODEBLOCK3
Testing
- - Use pytest (preferred) or unittest
- Name test files
test_*.py, test functions INLINECODE3 - Aim for focused unit tests, mock external dependencies
- Run before every commit: INLINECODE4
Docstrings
CODEBLOCK4
Quick Checklist
- - [ ] Syntax valid (
py_compile) - [ ] Tests pass (
pytest) - [ ] Type hints on public functions
- [ ] No hardcoded secrets
- [ ] f-strings, not
.format() or INLINECODE8 - [ ]
pathlib for file paths - [ ] Context managers for I/O
- [ ] No mutable default args
Python 编码指南
代码风格(PEP 8)
- - 缩进使用4个空格(绝不使用制表符)
- 最大行长度:88字符(Black默认)或79字符(严格PEP 8)
- 顶层定义前空两行,类内部方法间空一行
- 导入顺序:标准库 → 第三方库 → 本地库,每组内按字母排序
- 函数/变量使用蛇形命名法,类使用帕斯卡命名法,常量使用全大写命名法
提交前检查
bash
语法检查(始终执行)
python -m py_compile *.py
运行测试(如存在)
python -m pytest tests/ -v 2>/dev/null || python -m unittest discover -v 2>/dev/null || echo 未找到测试
格式检查(如可用)
ruff check . --fix 2>/dev/null || python -m black --check . 2>/dev/null
Python 版本
- - 最低要求: Python 3.10+(Python 3.9 将于2025年10月停止支持)
- 目标版本: 新项目使用 Python 3.11-3.13
- 绝不使用 Python 2 语法或模式
- 使用现代特性:match语句、海象运算符、类型提示
依赖管理
优先检查 uv,回退到 pip:
bash
优先使用 uv(如可用)
if command -v uv &>/dev/null; then
uv pip install <包名>
uv pip compile requirements.in -o requirements.txt
else
pip install <包名>
fi
使用 uv 创建新项目:uv init 或 uv venv && source .venv/bin/activate
Python 惯用模式
python
✅ 列表/字典推导式优于循环
squares = [x
2 for x in range(10)]
lookup = {item.id: item for item in items}
✅ 使用上下文管理器管理资源
with open(file.txt) as f:
data = f.read()
✅ 解包操作
first, *rest = items
a, b = b, a # 交换变量
✅ 请求宽恕比请求许可更容易(EAFP)优于三思而后行(LBYL)
try:
value = d[key]
except KeyError:
value = default
✅ 使用 f-string 进行格式化
msg = f你好 {name},你有 {count} 个项目
✅ 类型提示
def process(items: list[str]) -> dict[str, int]:
...
✅ 使用数据类/属性类作为数据容器
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
active: bool = True
✅ 使用 pathlib 替代 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
❌ 可变默认参数
def bad(items=[]): # 错误:在多次调用间共享
...
def good(items=None):
items = items or []
❌ 裸 except
try:
...
except: # 会捕获 SystemExit、KeyboardInterrupt
...
except Exception: # 更好的做法
...
❌ 全局状态
❌ from module import *
❌ 在循环中拼接字符串(应使用 join)
❌ == None(应使用 is None)
❌ len(x) == 0(应使用 not x)
测试
- - 使用 pytest(推荐)或 unittest
- 测试文件命名为 test.py,测试函数命名为 test
- 目标:聚焦的单元测试,模拟外部依赖
- 每次提交前运行:python -m pytest -v
文档字符串
python
def fetchuser(userid: int, include_deleted: bool = False) -> User | None:
根据用户ID从数据库获取用户。
参数:
user_id: 用户唯一标识符。
include_deleted: 如果为True,则包含软删除的用户。
返回:
找到则返回用户对象,否则返回None。
抛出异常:
DatabaseError: 如果数据库连接失败。
快速检查清单
- - [ ] 语法有效(py_compile)
- [ ] 测试通过(pytest)
- [ ] 公开函数有类型提示
- [ ] 无硬编码密钥
- [ ] 使用 f-string,而非 .format() 或 %
- [ ] 使用 pathlib 处理文件路径
- [ ] 使用上下文管理器处理 I/O 操作
- [ ] 无可变默认参数