Python Ruff 完整教學:用 Rust 打造的超快 Linter + Formatter 取代 Flake8 和 Black
為什麼 Ruff 這麼受歡迎
Ruff 比 Flake8 快 10-100 倍。10 萬行程式碼,Flake8 要 30 秒,Ruff 不到 1 秒。
Ruff 由 Astral 團隊用 Rust 開發,跟做 uv 套件管理器的同一個團隊。一個工具取代整個工具鏈:
- Flake8 → Ruff linting
- Black → Ruff formatting
- isort → Ruff 內建
- pyupgrade → Ruff 內建
- autoflake → Ruff 內建
安裝與快速上手
pip install ruff # 或 uv pip install ruff
ruff check . # 檢查品質
ruff check --fix . # 自動修復
ruff format . # 格式化
第一次跑 ruff check . 可能會噴一堆警告——大部分用 --fix 自動修復。
Linting 檢查
支援超過 800 條規則。建議至少啟用:
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]
E(pycodestyle)、F(Pyflakes)、I(isort)、UP(pyupgrade)、B(bugbear)、SIM(simplify)。自動排序 import、建議 f-string、找潛在 bug。
Formatting 格式化
Ruff formatter 刻意跟 Black 輸出幾乎一模一樣,遷移時程式碼不會有太大變動。
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = true
pyproject.toml 設定
[tool.ruff]
target-version = "py312"
line-length = 88
fix = true
[tool.ruff.lint]
select = ["E","F","I","UP","B","SIM","RUF"]
ignore = ["E501"]
[tool.ruff.lint.per-file-ignores]
"tests/**/*.py" = ["S101"]
[tool.ruff.lint.isort]
known-first-party = ["myproject"]
跟 Pydantic v2 專案搭配使用效果很好。
從 Flake8 + Black 遷移
- 安裝 Ruff
- 整合設定到 pyproject.toml
- 移除舊工具:
pip uninstall flake8 black isort autoflake pyupgrade - 更新 CI:
ruff check . && ruff format --check . - 更新 pre-commit hooks
15 分鐘搞定,CI 程式碼品質檢查從幾十秒降到幾秒。
CI/CD 整合
name: Lint
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
with:
args: "check"
- uses: astral-sh/ruff-action@v3
with:
args: "format --check"
VS Code 整合
安裝 Ruff 擴充套件,即時 linting + 存檔自動格式化:
{
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit",
"source.organizeImports.ruff": "explicit"
}
}
}
如果在用 FastAPI 開發 API,第一天就把 Ruff 設定好。
結語
Ruff 是 Python 生態系中最成功的「Rust 重寫」專案之一。一個設定檔、一個指令、一個 VS Code 擴充套件搞定程式碼品質。還在用 Flake8 + Black 的話,現在就是遷移到 Ruff 的最佳時機。
繼續閱讀
Python uv 專案管理完整教學:取代 pip 與 Poetry 的新一代開發工具
uv 是 Astral 團隊用 Rust 打造的 Python 專案管理工具,速度比 pip 快 10-100 倍,能一次取代 pip、Poetry、pyenv、virtualenv 等多個工具。這篇教學從安裝到專案管理、遷移指南一次搞懂。
相關文章
你可能也喜歡
探索其他領域的精選好文