Ruff 完全入门
面向零基础:什么是 Ruff、为什么需要它、如何安装使用、配置与实战
目录
一、什么是 Ruff
Ruff 是一个用 Rust 编写的 Python 代码检查器(Linter)和格式化工具(Formatter),由 Astral 公司(同时也开发了 uv 等工具)开发。它能够在毫秒级别完成对整个项目的代码检查和格式化。
Flake8 + Black + isort + pydocstyle + ... 的 Python 代码质量管家。
Ruff 的核心能力
Linter 检查代码风格和潜在错误(800+ 条内置规则)
Formatter 自动统一代码格式(与 Black 兼容的格式化风格)
自动修复 很多规则错误可以一键自动修复
极速 比传统工具快 10~100 倍
二、为什么需要 Ruff
2.1 Python 代码质量工具的传统困境
在 Ruff 出现之前,Python 开发者通常需要安装和使用多个独立工具来管理代码质量:
| 工具 | 作用 | 配置复杂度 |
|---|---|---|
Flake8 | 代码风格检查(PEP 8) | 需配置多个插件 |
Black | 代码格式化 | 需单独安装 |
isort | import 语句排序 | 需单独配置 |
pydocstyle | 文档字符串规范 | 需单独配置 |
pyupgrade | 代码升级建议 | 需单独安装 |
bandit | 安全检查 | 需单独安装 |
传统工具链的三大痛点
配置繁琐:每个工具都需要单独安装和配置,经常还要处理它们之间的兼容问题。
速度缓慢:大型项目运行一轮检查可能需要几十秒甚至几分钟,严重影响开发体验。
依赖混乱:多个工具带来了大量的依赖包,环境维护成本越来越高。
2.2 Ruff 的优势
All-in-One 一站式替代
Ruff 将 Linter(代码检查)和 Formatter(代码格式化)集成到一个工具中,内置 800+ 条规则,替代了 Flake8、Black、isort、pydocstyle 等几乎所有传统工具。
极速 性能提升 10~100 倍
Ruff 使用 Rust 语言编写,利用并行处理技术。在大型项目中,原本需要 30 秒的检查,Ruff 可能只需要 0.3 秒。
与 Black 兼容 格式统一
Ruff 的格式化器输出与 Black 完全一致,可以无缝替换 Black,无需担心格式化风格改变。
三、两个核心概念:Linter 与 Formatter
Linter 代码检查器
Linter 就像代码的“体检医生”——它分析代码,找出:
- 未使用的变量/导入
- 语法错误
- 不符合 PEP 8 规范的写法
- 潜在 Bug(如变量赋值后未使用)
- 安全问题
Linter 只检查,不修改代码(除非使用自动修复)。
Formatter 格式化工具
Formatter 就像代码的“美容师”——它自动调整:
- 缩进(空格/Tab)
- 行长度
- 空白间距
- 引号风格
- import 排序
Formatter 直接修改代码,统一格式。
❌ 未经 Format 的代码
import os,sys
def hello(name):
if name=="world":
print("Hello,world!")
else:
print("Hello,"+name+"!")
✅ Ruff Format 后的代码
import os
import sys
def hello(name):
if name == "world":
print("Hello, world!")
else:
print("Hello, " + name + "!")
四、安装 Ruff
pip 安装(推荐)
uv 安装(最快)
验证安装
pyproject.toml 依赖
五、代码检查(Lint)
5.1 基本检查
# 检查当前目录下所有 Python 文件 ruff check . # 检查单个文件 ruff check main.py # 检查并尝试自动修复 ruff check . --fix # 查看详细输出(显示问题所在行) ruff check . --output-format=concise
5.2 规则前缀速查
| 前缀 | 含义 | 示例 |
|---|---|---|
E | PEP 8 错误(Error) | E501 行过长 |
W | PEP 8 警告(Warning) | W291 行尾空白 |
F | Pyflakes(逻辑错误) | F401 未使用导入 |
I | isort(import 排序) | I001 import 未排序 |
N | 命名规范 | N802 函数名应小写 |
UP | pyupgrade(升级建议) | UP009 使用新语法 |
S | bandit(安全检查) | S101 不应使用 assert |
B | Bugbear(常见 Bug) | B008 默认参数中的可变对象 |
ruff check . --select E,W,F,I 表示只检查 E(PEP8 错误)、W(PEP8 警告)、F(逻辑错误)、I(import 排序)这四类规则。
六、代码格式化(Format)
# 格式化当前目录下所有 Python 文件 ruff format . # 格式化单个文件 ruff format main.py # 预览格式化效果(不实际修改) ruff format . --diff # 检查代码是否已格式化(CI 场景常用) ruff format . --check
ruff format . 会直接修改文件。如果不确定效果,先用 ruff format . --diff 预览改动。
格式化与 Linter 的区别
| 对比项 | ruff check | ruff format |
|---|---|---|
| 作用 | 检查代码质量和规范 | 调整代码外观格式 |
| 是否修改文件 | 默认不修改(–fix 可修复部分) | 直接修改文件 |
| 关注点 | 逻辑错误、未使用变量、安全问题 | 缩进、空格、换行、引号 |
| 规则数量 | 800+ 条可选规则 | 统一的格式化风格(类似 Black) |
七、配置 Ruff
Ruff 的配置写在项目根目录的 pyproject.toml 文件中(Python 项目的标准配置文件)。
7.1 常用配置示例
[tool.ruff]
# 目标 Python 版本(影响升级建议等规则)
target-version = "py311"
# 行长度限制(默认 88,Black 兼容)
line-length = 88
# 启用的规则集合
select = [
"E", # PEP 8 错误
"W", # PEP 8 警告
"F", # Pyflakes 逻辑错误
"I", # isort import 排序
"N", # 命名规范
"UP", # pyupgrade 升级建议
"B", # Bugbear
"SIM", # 简化代码
]
# 忽略某些规则
ignore = [
"E501", # 行过长(某些情况下太严格)
]
# 排除不需要检查的文件/目录
exclude = [
".git",
"__pycache__",
"build",
"dist",
"*.egg-info",
"migrations", # Django 迁移文件
]
[tool.ruff.format]
# 使用单引号还是双引号(默认双引号,Black 兼容)
quote-style = "double"
# 缩进使用 Tab 还是空格
indent-style = "space"
# 是否保留尾随逗号
skip-magic-trailing-comma = false
7.2 配置优先级
命令行参数优先级最高,会覆盖配置文件中的设置
八、与 VS Code 集成
最推荐的开发方式:安装 VS Code 的 Ruff 扩展,实现保存时自动检查和格式化。
- 安装 Ruff 扩展 打开 VS Code → 扩展商店 → 搜索 “Ruff” → 安装 Ruff(由 Astral 官方提供)
-
配置保存时自动格式化
“editor.formatOnSave”: true,
“[python]”: {
“editor.defaultFormatter”: “charliermarsh.ruff”,
“editor.codeActionsOnSave”: {
“source.fixAll.ruff”: “explicit”,
“source.organizeImports.ruff”: “explicit”
}
}
将以上配置添加到 VS Code 的
settings.json中。保存 Python 文件时,Ruff 会自动格式化代码并修复可自动修复的问题。 - 体验自动修复 打开一个有问题的 Python 文件(如未使用的导入),保存后 Ruff 会自动移除多余的导入并格式化代码。
source.fixAll.ruff 表示保存时自动修复可修复的 lint 错误;source.organizeImports.ruff 表示保存时自动整理 import 语句排序。
九、日常开发工作流
提交前的检查流程
- 格式化所有代码 ruff format .
- 检查并修复问题 ruff check . –fix
- 查看剩余无法自动修复的问题 ruff check . 手动修复剩余问题后,即可提交代码
package.json 或 Makefile 中添加快捷命令:ruff check . --fix && ruff format . — 一键检查并格式化整个项目。
十、常用命令速查表
| 场景 | 命令 |
|---|---|
| 检查项目 | ruff check . |
| 检查并自动修复 | ruff check . --fix |
| 格式化项目 | ruff format . |
| 预览格式化差异 | ruff format . --diff |
| 检查是否已格式化(CI) | ruff format . --check |
| 检查单个文件 | ruff check main.py |
| 查看帮助 | ruff --help |
| 查看版本 | ruff --version |
ruff check . --fix 和 ruff format .。
Ruff Complete Guide
For beginners: what Ruff is, why you need it, how to install, configure, and use it
Table of Contents
1. What is Ruff
Ruff is a Python linter and formatter written in Rust, developed by Astral (the same company behind uv). It can lint and format entire projects in milliseconds.
Flake8 + Black + isort + pydocstyle + ... for Python code quality.
Core Capabilities
Linter Check code style and catch errors (800+ built-in rules)
Formatter Auto-format code (Black-compatible style)
Auto-fix Many issues can be fixed with one command
Lightning fast 10-100x faster than traditional tools
2. Why Ruff
2.1 The Traditional Python Toolchain Problem
Before Ruff, Python developers needed multiple separate tools for code quality:
| Tool | Purpose | Config |
|---|---|---|
Flake8 | Style checking (PEP 8) | Multiple plugins needed |
Black | Code formatting | Separate install |
isort | Import sorting | Separate config |
pydocstyle | Docstring conventions | Separate config |
pyupgrade | Upgrade suggestions | Separate install |
bandit | Security checks | Separate install |
Three Pain Points of Traditional Tools
Tedious configuration: Each tool needs separate setup, and compatibility between them is often problematic.
Slow execution: Running checks on large projects can take 30+ seconds — painful for daily development.
Dependency bloat: Many tools bring in lots of dependencies, increasing environment maintenance cost.
2.2 Ruff’s Advantages
All-in-One One Tool to Rule Them All
Ruff integrates linter and formatter into a single tool with 800+ built-in rules, replacing Flake8, Black, isort, pydocstyle, and more.
Blazing Fast 10-100x Performance
Written in Rust with parallel processing. A 30-second check on a large project might finish in 0.3 seconds with Ruff.
Black-Compatible Consistent Formatting
Ruff’s formatter produces identical output to Black, allowing seamless replacement without style changes.
3. Linter vs Formatter
Linter Code Analyzer
A Linter is like a “code doctor” — it analyzes code and finds:
- Unused variables/imports
- Syntax errors
- PEP 8 violations
- Potential bugs
- Security issues
A Linter reads only, it doesn’t modify code (unless auto-fix is used).
Formatter Code Beautifier
A Formatter is like a “code stylist” — it automatically adjusts:
- Indentation
- Line length
- Whitespace
- Quote style
- Import sorting
A Formatter directly modifies code to enforce consistent style.
❌ Before Format
import os,sys
def hello(name):
if name=="world":
print("Hello,world!")
else:
print("Hello,"+name+"!")
✅ After Ruff Format
import os
import sys
def hello(name):
if name == "world":
print("Hello, world!")
else:
print("Hello, " + name + "!")
4. Installation
pip (Recommended)
uv (Fastest)
Verify Install
pyproject.toml
5. Code Checking (Lint)
5.1 Basic Checking
# Check all Python files in current directory ruff check . # Check a single file ruff check main.py # Check and attempt auto-fix ruff check . --fix # Detailed output (show affected lines) ruff check . --output-format=concise
5.2 Rule Prefix Reference
| Prefix | Category | Example |
|---|---|---|
E | PEP 8 Errors | E501 line too long |
W | PEP 8 Warnings | W291 trailing whitespace |
F | Pyflakes (logic) | F401 unused import |
I | isort (imports) | I001 unsorted imports |
N | Naming conventions | N802 function naming |
UP | pyupgrade | UP009 use modern syntax |
S | bandit (security) | S101 no assert in production |
B | Bugbear | B008 mutable default arg |
ruff check . --select E,W,F,I checks only E (PEP8 errors), W (warnings), F (logic), and I (import sorting) rules.
6. Code Formatting (Format)
# Format all Python files in current directory ruff format . # Format a single file ruff format main.py # Preview changes without modifying files ruff format . --diff # Check if code is formatted (useful in CI) ruff format . --check
ruff format . directly modifies files. Use ruff format . --diff to preview first.
check vs format Comparison
| Aspect | ruff check | ruff format |
|---|---|---|
| Purpose | Check code quality & standards | Adjust code appearance |
| Modifies files? | No by default (–fix for some) | Yes, directly |
| Focus | Logic errors, unused vars, security | Indentation, spaces, line breaks |
| Rules | 800+ optional rules | Unified formatting style (Black-like) |
7. Configuration
Ruff configuration lives in the project’s pyproject.toml file (the standard Python project config file).
7.1 Common Configuration
[tool.ruff]
# Target Python version
target-version = "py311"
# Line length limit (default 88, Black-compatible)
line-length = 88
# Enabled rule sets
select = [
"E", # PEP 8 errors
"W", # PEP 8 warnings
"F", # Pyflakes
"I", # isort
"N", # naming
"UP", # pyupgrade
"B", # bugbear
"SIM", # simplification
]
# Ignore specific rules
ignore = [
"E501", # line too long (sometimes too strict)
]
# Exclude files/directories
exclude = [
".git",
"__pycache__",
"build",
"dist",
"*.egg-info",
"migrations",
]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
7.2 Configuration Precedence
Command-line arguments have highest priority and override config file settings
8. VS Code Integration
Recommended workflow: install the Ruff VS Code extension for auto-format on save.
- Install the Ruff Extension VS Code → Extensions → Search “Ruff” → Install Ruff by Astral
-
Configure auto-format on save
“editor.formatOnSave”: true,
“[python]”: {
“editor.defaultFormatter”: “charliermarsh.ruff”,
“editor.codeActionsOnSave”: {
“source.fixAll.ruff”: “explicit”,
“source.organizeImports.ruff”: “explicit”
}
}
Add to VS Code’s
settings.json. Ruff auto-formats and fixes on save. - Test auto-fixing Open a Python file with issues (e.g., unused imports). Save and watch Ruff clean it up automatically.
source.fixAll.ruff auto-fixes lint errors on save; source.organizeImports.ruff sorts imports automatically.
9. Daily Workflow
Pre-Commit Check
- Format all code ruff format .
- Check and fix issues ruff check . –fix
- Review remaining issues ruff check . Manually fix any remaining issues, then commit
package.json or Makefile:ruff check . --fix && ruff format . — one command to lint and format the entire project.
10. Command Cheat Sheet
| Scenario | Command |
|---|---|
| Check project | ruff check . |
| Check and auto-fix | ruff check . --fix |
| Format project | ruff format . |
| Preview format changes | ruff format . --diff |
| Check formatting (CI) | ruff format . --check |
| Check single file | ruff check main.py |
| Help | ruff --help |
| Version | ruff --version |
ruff check . --fix and ruff format ..
