Python 的代码检查、格式化和类型检查
目录
先决条件
完成 开发您的应用程序。
概述
在本节中,您将学习如何为您的 Python 应用程序设置代码质量工具。这包括:
- 使用 Ruff 进行代码检查和格式化
- 使用 Pyright 进行静态类型检查
- 使用 pre-commit 钩子自动检查
使用 Ruff 进行代码检查和格式化
Ruff 是一个用 Rust 编写的极速 Python 代码检查器和格式化程序。它用一个统一的工具取代了 flake8、isort 和 black 等多个工具。
创建 pyproject.toml 文件
[tool.ruff]
target-version = "py312"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"ARG001", # unused arguments in functions
]
ignore = [
"E501", # line too long, handled by black
"B008", # do not perform function calls in argument defaults
"W191", # indentation contains tabs
"B904", # Allow raising exceptions without from e, for HTTPException
]使用 Ruff
运行这些命令来检查和格式化您的代码
# Check for errors
ruff check .
# Automatically fix fixable errors
ruff check --fix .
# Format code
ruff format .使用 Pyright 进行类型检查
Pyright 是一个快速的 Python 静态类型检查器,它与现代 Python 功能配合良好。
在 pyproject.toml 中添加 Pyright 配置
[tool.pyright]
typeCheckingMode = "strict"
pythonVersion = "3.12"
exclude = [".venv"]运行 Pyright
要检查代码中的类型错误
pyright设置 pre-commit 钩子
Pre-commit 钩子会在每次提交前自动运行检查。以下 .pre-commit-config.yaml 片段设置了 Ruff
https: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.2.2
hooks:
- id: ruff
args: [--fix]
- id: ruff-format要安装和使用
pre-commit install
git commit -m "Test commit" # Automatically runs checks摘要
在本节中,您学习了如何
- 配置和使用 Ruff 进行代码检查和格式化
- 设置 Pyright 进行静态类型检查
- 使用 pre-commit 钩子自动检查
这些工具有助于维护代码质量并在开发早期发现错误。
后续步骤
- 配置 GitHub Actions 以自动运行这些检查
- 自定义代码检查规则以匹配您团队的风格偏好
- 探索高级类型检查功能