Python Coding Guidelines技能使用说明
2026-03-27
新闻来源:网淘吧
围观:16
电脑广告
手机广告
Python 编码指南
代码风格 (PEP 8)
- 使用 4 个空格缩进(切勿使用制表符)
- 最大行长度:88 个字符 (Black 默认) 或 79 个字符 (严格遵循 PEP 8)
- 顶级定义前空两行,类内定义前空一行
- 导入顺序:标准库 → 第三方库 → 本地库,各组内按字母顺序排列
- 函数和变量使用蛇形命名法,类使用帕斯卡命名法,常量使用全大写加下划线
提交前
# 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:
# 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 模式
# ✅ 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):
...
需要避免的反模式
# ❌ 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
文档字符串
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-字符串,而非
.format()或% -
用于文件路径的pathlib模块用于I/O的上下文管理器 - 避免使用可变默认参数
- No mutable default args
文章底部电脑广告
手机广告位-内容正文底部
上一篇:Thinking Partner技能使用说明
下一篇:Xurl技能使用说明


微信扫一扫,打赏作者吧~