TL;DR: Ruff 是一個用 Rust 編寫的 Python 程式碼檢查工具(linter + formatter),速度比 Flake8 快 10-100 倍。它能在 0.5 秒內檢查完一個包含 30 萬行程式碼的超大規模專案。2026 年,Ruff 已經成為 Python 生態的事實標準程式碼品質工具,被 Instagram、PyTorch、Jupyter、Apache Airflow 等知名專案採用。本文將帶你從零開始使用 Ruff,包括安裝、設定、取代 Flake8/Black/isort 的完整遷移指南。
一、Ruff 是什麼?
Ruff 由 Astral 團隊開發(也是 uv 的同一團隊),用 Rust 編寫,定位為 Python 生態的一體化程式碼檢查工具。它整合了以下多個獨立工具的功能:
| 被替代工具 | 功能 | Ruff 規則前綴 |
|---|---|---|
| Flake8 | 程式碼風格檢查 | F, E, W |
| Black | 程式碼格式化 | - |
| isort | import 排序 | I |
| pyupgrade | Python 版本升級建議 | UP |
| pylint | 進階程式碼檢查 | PL, SIM, C901 |
| autoflake | 自動移除無用 import | F401, F841 |
為什麼 Ruff 這麼快?
- Rust 編譯:Rust 的效能遠超 Python,解析速度呈數量級差異
- 平行處理:自動利用多核 CPU 平行掃描檔案
- 零依賴:不需要 Python 執行環境,單一二進位檔案即可執行
- 增量快取:只檢查變更的檔案,二次執行幾乎瞬間完成
Ruff 的 GitHub 儲存庫:https://github.com/astral-sh/ruff ⭐ 截至 2026 年已突破 35,000 Star。
二、安裝 Ruff
Ruff 支援多種安裝方式,推薦使用 pip 或官方安裝指令碼:
# 方式 1:使用 pip(推薦)
pip install ruff
# 方式 2:使用 uv(更快)
uv tool install ruff
# 方式 3:macOS Homebrew
brew install ruff
# 方式 4:官方安裝指令碼
curl -LsSf https://astral.sh/ruff/install.sh | sh
# 驗證安裝
ruff --version
# 輸出:ruff 0.9.x
安裝完成後,Ruff 提供了兩個主要命令:
ruff check:程式碼檢查(linter 模式)ruff format:程式碼格式化(formatter 模式)
三、快速上手:5 分鐘檢查你的專案
建立一個測試檔案 hello.py:
import os
import sys
import json # unused
def hello_world():
x=1+2
print("hello world")
return x
if __name__ == "__main__":
hello_world()
3.1 執行程式碼檢查
ruff check hello.py
輸出範例:
hello.py:1:8: F401 [*] `os` imported but unused
hello.py:2:8: F401 [*] `sys` imported but unused
hello.py:3:8: F401 [*] `json` imported but unused
hello.py:5:1: W293 [*] Blank line contains whitespace
hello.py:7:6: E225 [*] Missing whitespace around operator
Found 5 errors.
[*] 5 fixable with the `--fix` option.
Ruff 精準識別了 5 個問題:3 個未使用的 import、1 個多餘空行、1 個運算子周圍缺少空格。每個錯誤都標註了是否可以用 --fix 自動修復。
3.2 自動修復
ruff check --fix hello.py
執行後檔案內容自動修正:
def hello_world():
x = 1 + 2
print("hello world")
return x
if __name__ == "__main__":
hello_world()
3.3 程式碼格式化
ruff format hello.py
ruff format 類似於 Black,會自動調整縮排、空行、引號風格等,確保整個專案程式碼風格統一。
四、設定檔案詳解
在專案根目錄建立 pyproject.toml 來設定 Ruff:
[tool.ruff]
# 目標 Python 版本
target-version = "py312"
# 行長度限制
line-length = 88
# 要檢查的目錄
src = ["src", "tests"]
# 排除的目錄
exclude = [
".git",
".venv",
"__pycache__",
"build",
"dist",
]
[tool.ruff.lint]
# 啟用的規則集
select = [
"E", # pycodestyle 錯誤
"W", # pycodestyle 警告
"F", # pyflakes
"I", # isort(import 排序)
"UP", # pyupgrade(版本升級建議)
"B", # flake8-bugbear(常見 bug 模式)
"SIM", # flake8-simplify(程式碼簡化)
"RUF", # Ruff 自帶規則
]
# 忽略的規則
ignore = [
"E501", # 行太長(交給 formatter 處理)
"E402", # import 不在檔案頂部(某些指令碼需要)
]
# 最大允許複雜度
mccabe.max-complexity = 10
[tool.ruff.lint.per-file-ignores]
# 測試檔案忽略部分規則
"tests/**/*.py" = ["S101", "PLR2004"]
# 遷移檔案忽略所有規則
"**/migrations/*.py" = ["ALL"]
[tool.ruff.format]
# 引號風格:單引號或雙引號
quote-style = "double"
# 縮排類型
indent-style = "space"
# 末尾換行
skip-magic-trailing-comma = false
4.1 常用規則集說明
| 規則集 | 說明 | 典型規則 |
|---|---|---|
| E/W | pycodestyle 風格檢查 | E501 行太長,W292 檔案末尾缺少換行 |
| F | pyflakes 錯誤偵測 | F401 未使用 import,F841 未使用變數 |
| I | import 排序 | I001 import 順序不正確 |
| UP | Python 版本升級 | UP006 使用 list 而非 typing.List |
| B | bugbear 常見 bug | B006 可變預設參數,B007 未使用迴圈變數 |
| SIM | 程式碼簡化 | SIM101 重複 isinstance,SIM108 使用三元運算式 |
| RUF | Ruff 自有規則 | RUF001 模糊字元,RUF005 展開而非拼接 |
五、取代 Black/isort/Flake8 完整遷移指南
如果你的專案之前使用 Black + isort + Flake8 組合,可以完全遷移到 Ruff。
5.1 解除安裝舊工具
pip uninstall black isort flake8 autoflake pyupgrade -y
5.2 設定 Ruff 行為相容
在 pyproject.toml 中新增與 Black 相容的設定:
[tool.ruff]
line-length = 88 # Black 預設行寬
target-version = "py312"
[tool.ruff.format]
quote-style = "double" # Black 預設雙引號
indent-style = "space"
[tool.ruff.lint]
select = ["E", "W", "F", "I"]
5.3 批次修復整個專案
# 第一步:格式化所有 Python 檔案
ruff format .
# 第二步:檢查並自動修復
ruff check --fix .
# 第三步:檢視剩餘問題(不自動修復)
ruff check .
5.4 與 pre-commit 整合
建立 .pre-commit-config.yaml:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.9.0
hooks:
# 先格式化
- id: ruff-format
# 再檢查
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
安裝 pre-commit hook:
pip install pre-commit
pre-commit install
現在每次 git commit 時,Ruff 會自動格式化和檢查暫存的檔案。
六、CI/CD 整合實戰
6.1 GitHub Actions
name: Ruff Check
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Ruff
run: pip install ruff
- name: Run Ruff format check
run: ruff format --check .
- name: Run Ruff lint
run: ruff check --output-format=github .
6.2 GitLab CI
ruff:
image: python:3.12-slim
stage: test
script:
- pip install ruff
- ruff format --check .
- ruff check .
allow_failure: true # 初期可以先允許失敗
6.3 在大型專案中最佳化效能
對於超大規模專案,可以使用以下最佳化策略:
# 只檢查變更的檔案(CI 場景)
ruff check --diff .
# 輸出 SARIF 格式(用於 GitHub Code Scanning)
ruff check --output-format=sarif . > results.sarif
# 只檢查特定規則
ruff check --select=F,E .
# 檢視 Ruff 的設定和快取狀態
ruff check --show-settings .
七、Ruff vs 競品對比
| 特性 | Ruff | Flake8 | Black + isort |
|---|---|---|---|
| 語言 | Rust | Python | Python |
| 速度 | ⚡ 極快(毫秒級) | 慢(秒級) | 中等 |
| 功能範圍 | Linter + Formatter | 僅 Linter | 僅 Formatter |
| 外掛生態 | 內建規則 | 豐富外掛 | 外掛擴充 |
| 自動修復 | ✅ 支援 | ❌ 不支援 | ✅ 支援 |
| 設定方式 | pyproject.toml | .flake8/.cfg | pyproject.toml |
| Python 依賴 | 無需 Python | 需要 | 需要 |
效能實測
在一個 50 萬行程式碼的專案中:
- Ruff check:0.3 秒
- Flake8:45 秒
- pylint:120 秒
Ruff 比 Flake8 快約 150 倍,比 pylint 快約 400 倍。
八、進階用法
8.1 自訂規則
Ruff 支援透過 pyproject.toml 自訂規則的嚴重等級:
[tool.ruff.lint]
select = ["E", "F", "W"]
# 將某些規則設為警告而非錯誤
[tool.ruff.lint.flake8-errmsg]
max-string-length = 20
[tool.ruff.lint.pydocstyle]
convention = "google" # 或 "numpy", "pep257"
8.2 與 IDE 整合
VS Code:安裝官方 Ruff 擴充套件,支援: - 即時 lint 檢查 - 儲存時自動 format - 一鍵修復建議
// .vscode/settings.json
{
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.codeActionsOnSave": {
"source.fixAll.ruff": "explicit"
}
}
}
PyCharm:透過 External Tools 設定:
- 開啟 Settings → Tools → External Tools
- 新增 Ruff:Program 為 ruff,Arguments 為 check --fix $FilePath$
8.3 增量檢查(Watch 模式)
# 監聽檔案變化,自動重新檢查
ruff check --watch .
8.4 產生 HTML 報告
# 輸出 JSON 格式,可以用 jq 處理
ruff check --output-format=json . | jq '.'
# 或使用 sarif 格式配合 GitHub Code Scanning
ruff check --output-format=sarif . > ruff-results.sarif
九、常見問題
Q1:Ruff 能完全替代 Flake8 嗎?
大部分場景可以。Ruff 內建了 Flake8 的大部分規則(E、W、F 系列),以及一些流行外掛的規則(bugbear、eradicate 等)。但如果你使用了非常小眾的 Flake8 外掛,可能需要確認 Ruff 是否有對應實作。
Q2:Ruff 能替代 pylint 嗎?
不完全可以。Ruff 側重於程式碼風格和常見 bug 偵測,而 pylint 有更深入的程式碼品質分析(如複雜度評分、重複程式碼偵測)。對於日常開發,Ruff 已經足夠;對於嚴格的品質稽核,可以 Ruff + pylint 配合使用。
Q3:Ruff 的 --fix 安全嗎?
非常安全。Ruff 的自動修復僅針對有明確修復策略的規則,不會做語意層面的改動。修復前建議先用 ruff check --diff . 預覽變更。
Q4:Ruff 支援哪些 Python 版本?
Ruff 本身支援 Python 3.7 - 3.13 的程式碼檢查。透過 target-version 設定,可以指定目標 Python 版本並取得相應的升級建議。
十、總結
Ruff 正在成為 Python 生態的程式碼品質基礎設施。憑藉 Rust 帶來的極致效能、豐富的內建規則、以及一體化的 linter + formatter 體驗,它讓 Python 專案的程式碼品質管理變得前所未有的簡單和高效。
行動建議:
- 用
pip install ruff安裝 - 在專案中執行
ruff check --fix .+ruff format . - 設定
pyproject.toml自訂規則 - 整合到 pre-commit 和 CI/CD 流水線
你的專案程式碼品質會立刻得到一個巨大的提升,而整個過程只需要幾分鐘。
相關連結:
- Ruff 官方文件:https://docs.astral.sh/ruff/
- Ruff GitHub:https://github.com/astral-sh/ruff
- uv 工具(Ruff 同團隊):https://docs.astral.sh/uv/
- 相關資源:linux-tutorials/linux-fileformat.md — 了解 Python 檔案格式
- 相關資源:linux-tutorials/ubuntu-dependency.md — Python 套件管理基礎