跳到主要内容

Lint 与格式化

问题

Python 项目如何做代码规范和类型检查?

答案

Ruff(2024 年主流)

Ruff 是 Rust 编写的超快 Python linter + formatter,替代 Flake8 + isort + Black:

pyproject.toml
[tool.ruff]
target-version = "py311"
line-length = 120

[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"UP", # pyupgrade
]
ignore = ["E501"] # 行长由 formatter 控制

[tool.ruff.format]
quote-style = "double"
ruff check .          # Lint
ruff check . --fix # 自动修复
ruff format . # 格式化

mypy(类型检查)

pyproject.toml
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true

[[tool.mypy.overrides]]
module = "tests.*"
allow_untyped_defs = true
mypy src/

pre-commit

提交前自动检查:

.pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.13.0
hooks:
- id: mypy
additional_dependencies: [types-requests]
pre-commit install           # 安装 git hooks
pre-commit run --all-files # 手动运行

工具链推荐

用途推荐工具替代
Lint + FormatRuffFlake8 + Black + isort
类型检查mypyPyright (Pylance)
Git Hookspre-commitHusky(前端)
安全检查Bandit

常见面试问题

Q1: Ruff 为什么能替代那么多工具?

答案

Ruff 用 Rust 实现了 Flake8、isort、pyupgrade、Black 等工具的规则,统一配置在 pyproject.toml。速度比 Flake8 快 10-100 倍,且规则兼容。

Q2: mypy strict 模式包含哪些检查?

答案

strict = true 相当于开启:无类型注解报错、禁止 Any、检查返回值、检查未使用忽略等。刚开始可以用 --strict 的子集逐步开启。

相关链接