Tool Configuration
It is recommended to use the following tools to ensure Python code quality:
- ruff — Code formatting + lint checks (replaces black, isort, flake8)
- basedpyright — Strict static type checking (replaces mypy)
Quick Commands
# 格式化代码(自动修复)
ruff format .
# Lint 检查(自动修复可修复的问题)
ruff check . --fix
Check only, do not fix
ruff check . --no-fix
Type checkingbasedpyright
Type-check a single filebasedpyright src/module.py
## 推荐 ruff 配置示例(pyproject.toml)
```toml
[tool.ruff]
target-version = "py310"
line-length = 120
fix = true
[tool.ruff.lint]
select = [
"E", # pycodestyle 错误
"W", # pycodestyle 警告
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"SIM", # flake8-simplify
"RET", # flake8-return
"N", # pep8-naming
]
ignore = [
"E501", # 行长度(由 formatter 控制)
]
[tool.ruff.lint.isort]
known-first-party = ["your_package_name"] # 替换为实际的包名
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
Recommended basedpyright configuration example (pyproject.toml)
[tool.basedpyright]
pythonVersion = "3.10"
typeCheckingMode = "strict"
reportMissingImports = true
reportMissingTypeStubs = false
# 存量项目可先从 standard 迁移,再逐步提升到 strict
Code Style Standards
Type Annotations
- AlwaysAdd type annotations for function parameters and return values
- Use
X | Noneinstead ofOptional[X](Python 3.10+) - Use
X | Yinstead ofUnion[X, Y](Python 3.10+) - Use
list[X]、dict[K, V]、tuple[X, ...]instead ofList、Dict、Tuple
# ✅ 正确
def process(data: list[str], limit: int | None = None) -> dict[str, int]:
...
# ❌ 错误
from typing import List, Optional, Dict
def process(data: List[str], limit: Optional[int] = None) -> Dict[str, int]:
...
String Formatting
- Prefer f-strings, avoid using
%formatting and.format()
# ✅ 正确
name = "world"
message = f"Hello, {name}!"
# ❌ 错误
message = "Hello, %s!" % name
message = "Hello, {}!".format(name)
Import Order
Follow the isort convention (ruff handles this automatically):
- Standard library
- Third-party libraries
- Local modules
# ✅ 正确
import os
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from mypackage.utils import helper
Docstrings
Public APIs should use Google-style docstrings:
- Public modules, public classes, and public functions should have docstrings
- Short private functions inside a module may not be required to have them if their behavior is sufficiently intuitive
def calculate_discount(price: float, rate: float) -> float:
"""计算折扣后的价格。
Args:
price: 原始价格,必须为正数。
rate: 折扣率,范围 0.0 到 1.0。
Returns:
折扣后的价格。
Raises:
ValueError: 当 rate 不在 [0, 1] 范围内时抛出。
Examples:
>>> calculate_discount(100.0, 0.2)
80.0
"""
if not 0.0 <= rate <= 1.0:
raise ValueError(f"折扣率必须在 0 到 1 之间,当前值: {rate}")
return price * (1 - rate)
Naming Conventions
| Type | Style | Example |
|---|---|---|
| Module | snake_case | user_service.py |
| Class | PascalCase | UserService |
| Function/Method | snake_case | get_user_by_id |
| Constant | UPPER_SNAKE_CASE | MAX_RETRIES |
| Private | Prefix _ |
_internal_state |
| Type Variable | PascalCase + T | UserT |
Exception Handling
- Catch specific exceptions, do not use bare
except: - Exception messages should include context
# ✅ 正确
try:
result = risky_operation()
except ValueError as e:
logger.error(f"参数无效: {e}")
raise
# ❌ 错误
try:
result = risky_operation()
except:
pass
CI Integration
It is recommended to integrate quality checks in GitHub Actions:
- name: Lint and Format Check
run: |
ruff format --check .
ruff check . --no-fix
- name: Type Check
run: basedpyright
Common ruff errors and fixes
| Rule | Description | Fix Method |
|---|---|---|
F401 |
Unused import | Delete the unused import |
B006 |
Mutable default argument | Use None instead of a mutable default value |
SIM108 |
Ternary expression can be simplified | Use the ternary operator |
UP006 |
Use of old-style type annotations | Use built-in types instead of the typing module |
RET504 |
Unnecessary assignment before return | Return the expression directly |