用 Ruff 打造自動化 Python 格式化與靜態檢查(VS Code 實戰)
在現代 Python 專案中,維持一致的程式碼風格與自動排版已成為團隊協作的基本需求。Ruff 是一套超快速、全方位的 Python linter 與 formatter,能同時做到靜態檢查、import 排序與自動格式化。
本文將介紹 Ruff 的安裝、基本設定與常見用法,以及如何在 VS Code 開發環境下,讓 Ruff 在每次儲存檔案時自動執行,確保團隊程式碼品質一致。
Ruff 是什麼?
Ruff 是用 Rust 開發的 Python 靜態分析工具,主打「快」與「多合一」:
- Linter:檢查語法錯誤、潛在 bug、PEP8 風格等
- Formatter:自動排版、統一引號、行寬等
- Import 排序:自動整理 import 順序
如何安裝 Ruff
可以直接用 pip 安裝:
pip install ruff
如果專案有 pyproject.toml
,也可以直接在 dev dependencies 加入:
[dependency-groups]
dev = [
"ruff>=0.12.0",
]
設定 Ruff:pyproject.toml
Ruff 支援在 pyproject.toml
設定,常見設定如下:
[tool.ruff]
select = ["E", "F", "I"] # 啟用基本錯誤檢查與 import 排序
exclude = ["venv", ".venv", "__pycache__", "migrations"] # 排除目錄
line-length = 88
target-version = "py311"
fix = true # 預設自動修復違規
[tool.ruff.format]
quote-style = "single" # 統一用單引號
line-ending = "lf" # 換行符號
[tool.ruff.isort]
combine-as-imports = true # 排序 import 時合併 as 語法
VS Code 設定:儲存時自動執行 Ruff
安裝 Python 與 Ruff 擴充套件
編輯 .vscode/settings.json
在專案根目錄建立或編輯 .vscode/settings.json
,加入:
{
"python.formatting.provider": "ruff",
"editor.formatOnSave": true,
"ruff.enable": true,
"ruff.formatOnSave": true,
"python.linting.enabled": true,
"python.linting.ruffEnabled": true
}
若同時有安裝 black/autopep8/yapf,請確保
python.formatting.provider
設為"ruff"
。
實際效果
- 每次儲存 Python 檔案時,Ruff 會自動格式化、排序 import、修正違規
- 所有格式與靜態檢查規則都依
pyproject.toml
設定 - 團隊協作時,程式碼風格一致,減少 review friction
常用指令
自動格式化所有 Python 檔案
ruff format .
檢查並自動修正違規
ruff check . --fix
只檢查,不修正
ruff check .
結論
Ruff 結合 VS Code 的自動化設定,能大幅提升 Python 專案的開發效率與品質。
只要簡單設定,從此不再為格式與 import 排序煩惱!