python-standards
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Standards
Python 开发规范
Modern Python with uv + ruff + mypy + pytest. All config in pyproject.toml.
基于 uv + ruff + mypy + pytest 的现代 Python 开发方式,所有配置统一在 pyproject.toml 中管理。
Toolchain
工具链
| Tool | Purpose |
|---|---|
| uv | Dependencies + virtual envs (lockfile: |
| ruff | Linting + formatting (replaces black, isort, flake8) |
| mypy | Type checking (strict mode) |
| pytest | Testing + coverage |
bash
undefined| 工具 | 用途 |
|---|---|
| uv | 依赖管理 + 虚拟环境(锁文件: |
| ruff | 代码检查 + 格式化(替代 black、isort、flake8) |
| mypy | 类型校验(严格模式) |
| pytest | 测试 + 覆盖率统计 |
bash
undefinedSetup
Setup
uv init && uv add <deps> && uv sync
uv init && uv add <deps> && uv sync
Daily workflow
Daily workflow
uv run ruff check . --fix && uv run ruff format .
uv run mypy . && uv run pytest
undefineduv run ruff check . --fix && uv run ruff format .
uv run mypy . && uv run pytest
undefinedType Hints
类型提示
All functions and classes must have explicit type hints:
python
def fetch_user(user_id: str) -> User | None:
"""Fetch user by ID."""
...
def process_items(items: list[Item]) -> dict[str, int]:
...mypy strict mode:
toml
[tool.mypy]
strict = true
disallow_untyped_defs = true
disallow_any_generics = true所有函数和类必须添加明确的类型提示:
python
def fetch_user(user_id: str) -> User | None:
"""Fetch user by ID."""
...
def process_items(items: list[Item]) -> dict[str, int]:
...mypy 严格模式配置:
toml
[tool.mypy]
strict = true
disallow_untyped_defs = true
disallow_any_generics = truePackage Structure
包结构
Feature-based, not layer-based:
src/myproject/
users/ # Domain
__init__.py # Public API: __all__ = ['User', 'UserService']
models.py
services.py
orders/ # Another domain
shared/ # Cross-cutting concerns采用基于功能的结构,而非分层结构:
src/myproject/
users/ # Domain
__init__.py # Public API: __all__ = ['User', 'UserService']
models.py
services.py
orders/ # Another domain
shared/ # Cross-cutting concernsError Handling
错误处理
Catch specific exceptions with context:
python
try:
result = parse_config(path)
except FileNotFoundError:
logger.warning(f"Config not found: {path}")
return defaults
except json.JSONDecodeError as e:
raise ConfigError(f"Invalid JSON in {path}") from eNever: bare , silent swallowing, .
except:except Exception捕获特定异常并附带上下文信息:
python
try:
result = parse_config(path)
except FileNotFoundError:
logger.warning(f"Config not found: {path}")
return defaults
except json.JSONDecodeError as e:
raise ConfigError(f"Invalid JSON in {path}") from e禁止:使用无限制的 、静默忽略异常、 捕获所有异常。
except:except Exceptionpyproject.toml
pyproject.toml 配置
Single source of truth (no setup.py, requirements.txt):
toml
[project]
name = "myproject"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = ["httpx", "pydantic"]
[project.optional-dependencies]
dev = ["pytest", "mypy", "ruff"]
[tool.ruff]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "S", "ANN"]
line-length = 88
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--cov=src", "--cov-fail-under=85"]单一配置源(不再使用 setup.py、requirements.txt):
toml
[project]
name = "myproject"
version = "1.0.0"
requires-python = ">=3.11"
dependencies = ["httpx", "pydantic"]
[project.optional-dependencies]
dev = ["pytest", "mypy", "ruff"]
[tool.ruff]
select = ["E", "W", "F", "I", "B", "UP", "SIM", "S", "ANN"]
line-length = 88
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--cov=src", "--cov-fail-under=85"]Anti-Patterns
反模式
- without documented justification
Any - Layer-based folders (,
/controllers,/models)/views - Circular imports
- Legacy tools (pip, black+isort, flake8)
- Multiple config files
- comments without justification
noqa
- 无文档说明的情况下使用 类型
Any - 采用分层文件夹结构(如 、
/controllers、/models)/views - 循环导入
- 使用旧版工具(pip、black+isort、flake8)
- 存在多个配置文件
- 无合理理由使用 注释
noqa
References
参考资料
- testing-patterns.md - pytest, fixtures, parametrize
- ruff-config.md - Complete ruff rule configuration
- testing-patterns.md - pytest、fixtures、参数化测试
- ruff-config.md - 完整的 ruff 规则配置