Ruff 深度实战指南:Rust 打造的高速 Python 代码检查器与格式化工具
Ruff 是一个用 Rust 编写的极速 Python linter 与代码格式化工具,目标是单一工具替代 Flake8、Black、isort、pydocstyle、pyupgrade、autoflake 等一整套传统 Python 工具链。本文以仓库根目录 README.md 为主体骨架,结合 crates/ 下的 Rust 源码,完整覆盖安装、check/format 命令、配置体系、规则系统与缓存机制,帮助读者在真实项目中落地 Ruff 并理解其底层实现。
一、定位与核心特性
Ruff 的自我定位是"比现有工具快一个数量级以上,同时把更多功能整合到单一常见接口之下"(见 README.md 的 Overview 一节)。围绕这一定位,仓库文档给出了如下关键特性:
- 速度:比 Flake8 等传统 linter 和 Black 等传统 formatter 快 10–100 倍。README 中的基准图即"从零开始 lint CPython 代码库"的耗时对比;
- 分发方式:通过
pip可安装,也提供独立二进制安装脚本; - 配置兼容:原生支持
pyproject.toml; - 语言兼容:README 明确标注支持 Python 3.14 语法;
- 行为对齐(drop-in parity):linter 对齐 Flake8,导入排序对齐 isort,格式化工具对齐 Black;
- 内置缓存:避免重复分析未变更的文件;
- 自动修复(fix):例如自动移除未使用的导入;
- 规则规模:内置 900 余条规则,其中大量规则是对 flake8-bugbear 等流行 Flake8 插件的原生 Rust 重实现;
- 编辑器集成:提供 VS Code 等编辑器的第一方集成(仓库内有 LSP 服务实现);
- Monorepo 友好:支持层级式、级联式配置发现。
从源码结构看,上述特性分别落在不同的 workspace crate 中(见 Cargo.toml 的 [workspace.dependencies] 段,版本 0.16.5、Rust edition 2024):
| 能力 | 对应 crate |
|---|---|
CLI 入口(ruff 可执行文件) |
crates/ruff |
| 900+ 规则的实现与注册 | crates/ruff_linter |
| Python 语法树与解析器 | crates/ruff_python_ast、crates/ruff_python_parser |
| 格式化引擎(Black 风格) | crates/ruff_python_formatter |
| 文件级缓存 | crates/ruff_cache |
| 配置解析与默认值 | crates/ruff_workspace |
| 语义模型(作用域、导入分析) | crates/ruff_python_semantic |
这种"解析、AST、语义、lint、格式化、缓存"分层解耦的结构,正是 Ruff 能在单个二进制中同时提供 lint 与 format 能力的工程基础。
二、安装
2.1 使用 uvx 直接调用(免安装)
uvx ruff@0.16.5 check # Lint all files in the current directory.
uvx ruff@0.16.5 format # Format all files in the current directory.
2.2 通过包管理器安装
# With uv.
uv tool install ruff@latest # Install Ruff globally.
uv add --dev ruff # Or add Ruff to your project.
# With pip.
pip install ruff
# With pipx.
pipx install ruff
2.3 独立二进制安装脚本(0.5.0 起提供)
# On macOS and Linux.
curl -LsSf https://astral.sh/ruff/install.sh | sh
# On Windows.
powershell -c "irm https://astral.sh/ruff/install.ps1 | iex"
# For a specific version.
curl -LsSf https://astral.sh/ruff/0.16.5/install.sh | sh
powershell -c "irm https://astral.sh/ruff/0.16.5/install.ps1 | iex"
此外 README 指出 Ruff 也可通过 Homebrew、Conda(conda-forge 频道)及其他多种包管理器安装。注意仓库中的安装脚本类资产并不在本仓库内,安装命令中的域名链接属于官方发布渠道,此处照录原文仅作命令参考;本文不输出任何外部站点链接。
三、基本命令:ruff check 与 ruff format
Ruff 的两条主命令是 check(检查/修复)与 format(格式化),二者共享同一套目标文件解析逻辑(目录递归、*.py 通配、单文件、以及 @arguments.txt 形式的参数文件)。
3.1 作为 linter
ruff check # Lint all files in the current directory (and any subdirectories).
ruff check path/to/code/ # Lint all files in `/path/to/code` (and any subdirectories).
ruff check path/to/code/*.py # Lint all `.py` files in `/path/to/code`.
ruff check path/to/code/to/file.py # Lint `file.py`.
ruff check @arguments.txt # Lint using an input file, treating its contents as newline-delimited command-line arguments.
3.2 作为 formatter
ruff format # Format all files in the current directory (and any subdirectories).
ruff format path/to/code/ # Format all files in `/path/to/code` (and any subdirectories).
ruff format path/to/code/*.py # Format all `.py` files in `/path/to/code`.
ruff format path/to/code/to/file.py # Format `file.py`.
ruff format @arguments.txt # Format using an input file, treating its contents as newline-delimited command-line arguments.
其中 --fix 开关启用自动修复(如移除未使用的导入),这在下面 pre-commit 示例中可以看到。CLI 参数定义集中在 crates/ruff/src/args.rs,check 与 format 子命令的行为集成测试位于 crates/ruff/tests/integration_test.rs 及 crates/ruff/tests/cli/lint.rs。后者包含大量 --select RUF015 之类的真实 CLI 用例(如 lint.rs 中的 RUF015 测试),覆盖了 noqa 抑制、ruff: ignore[...] 指令与 --fix 交互等细节。
四、CI 集成:pre-commit 与 GitHub Action
4.1 pre-commit 钩子
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.16.5
hooks:
# Run the linter.
- id: ruff-check
args: [ --fix ]
# Run the formatter.
- id: ruff-format
(yaml 中的 repo 值为 README 原文保留的钩子仓库地址,是 pre-commit 框架的必填字段。)
4.2 GitHub Action
name: Ruff
on: [ push, pull_request ]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/ruff-action@v3
两条集成路径的共同点是把"lint + fix"放在提交前、"lint + format"放在推送/PR 时,利用 Ruff 的速度把检查成本压缩到可忽略(README 引用了用户"把 Ruff 加进 commit hook"的实践经验)。
五、配置体系
Ruff 可配置的文件有 pyproject.toml、ruff.toml 或 .ruff.toml 三种(详见 docs/configuration.md)。若在 pyproject.toml 中配置,每个 section 需要加 tool.ruff 前缀,例如 [lint] 写作 [tool.ruff.lint]。
5.1 默认配置的完整等价物
如果不提供任何配置,Ruff 的默认配置等价于下面这份 ruff.toml(直接来自 README.md 的 Configuration 一节,逐行继承):
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]
# Same as Black.
line-length = 88
indent-width = 4
# Assume Python 3.10
target-version = "py310"
[lint]
# select = [...] # See the Default Rules page for the full listing.
ignore = []
# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[format]
# Like Black, use double quotes for strings.
quote-style = "double"
# Like Black, indent with spaces, rather than tabs.
indent-style = "space"
# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false
# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"
要点解读:
line-length = 88与 Black 保持一致,避免 lint 与 format 因行宽不同互相打架;dummy-variable-rgx允许下划线前缀的"未使用变量"(如_),这是F841类规则的默认豁免模式;[format]段默认双引号、空格缩进、尊重 magic trailing comma、自动检测换行符,全部与 Black 对齐;exclude默认排除 26 个常见目录,.ruff_cache本身也在其中(缓存目录自排除)。
5.2 命令行覆盖配置
部分配置项有专用命令行参数(规则启停、文件发现、日志级别):
ruff check --select F401 --select F403 --quiet
其余配置项通过"万能" --config 参数以 TOML 片段形式传入:
ruff check --config "lint.per-file-ignores = {'some_file.py' = ['F841']}"
5.3 配置在源码中的落点
配置解析的结果类型是 crates/ruff_workspace/src/settings.rs 中的 Settings 结构。从源码结构看(settings.rs 的 Default 实现),全局默认值包含:
cache_dir:按项目根计算(对应exclude中的.ruff_cache);fix: false、fix_only: false:自动修复默认关闭,需显式传--fix;output_format、show_fixes、unsafe_fixes等输出与修复策略;- 四个嵌套子配置:
linter(LinterSettings)、file_resolver(含exclude/include/respect_gitignore等字段,见 FileResolverSettings)、formatter、analyze。
仓库根目录还维护了完整的 ruff.schema.json,可用于编辑器对 ruff.toml/pyproject.toml 做 JSON Schema 校验与自动补全。
5.4 Preview 模式
通过配置文件中 preview = true 或命令行 --preview 启用,可提前试用最新的 lint 规则、格式化风格变更与接口更新。README 特别提示:preview 特性集合是"不稳定的、可能在稳定前变化"的,生产项目建议只在评估后开启。
六、规则系统
Ruff 内置超过 900 条 lint 规则,且无论规则源自哪个工具,全部由 Rust 原生重实现为第一方能力(不存在运行时插件加载)。
默认启用的规则类别:F(Pyflakes)、E(pycodestyle Error)、B(bugbear)、UP(pyupgrade)与 RUF(Ruff 自有规则),外加许多其他规则,但刻意排除了与格式化工具(ruff format 或 Black)职责重叠的风格类规则——这是避免"lint 与 format 互相冲突"的关键设计,README 建议新手直接从默认规则集起步(零配置即可捕获未使用导入等大量常见错误)。
除默认集外,Ruff 重实现了一批最流行的 Flake8 插件与质量工具,包括:autoflake、eradicate、flake8-2020、flake8-annotations、flake8-async、flake8-bandit、flake8-blind-except、flake8-boolean-trap、flake8-bugbear、flake8-builtins、flake8-commas、flake8-comprehensions、flake8-copyright、flake8-datetimez、flake8-debugger、flake8-django、flake8-docstrings、flake8-errmsg、flake8-executable、flake8-future-annotations、flake8-gettext、flake8-implicit-str-concat、flake8-import-conventions、flake8-logging、flake8-logging-format、flake8-no-pep420、flake8-pie、flake8-print、flake8-pyi、flake8-pytest-style、flake8-quotes、flake8-raise、flake8-return、flake8-self、flake8-simplify、flake8-slots、flake8-super、flake8-tidy-imports、flake8-todos、flake8-type-checking、flake8-use-pathlib、flynt、isort、mccabe、pandas-vet、pep8-naming、pydocstyle、pygrep-hooks、pylint-airflow、pyupgrade、tryceratops、yesqa。
在源码层面,所有规则按上游插件组织在 crates/ruff_linter/src/rules/ 目录下(3000 余个文件,含 2189 个 .snap 快照测试),规则注册表位于 crates/ruff_linter/src/registry.rs,规则代码(如 F401、RUF015)的映射定义在 crates/ruff_linter/src/codes.rs。规则选择语法(--select F401、per-file-ignores 等)在 crates/ruff_linter/src/rule_selector.rs 中实现。
七、性能与架构:从源码看 Ruff 为什么快
README 承诺的"10–100 倍速度"来自几个在源码中可验证的工程决策:
- 单一 Rust 二进制:解析、lint、format 共享同一次词法/语法分析结果。AST 由 crates/ruff_python_ast 提供(配合 crates/ruff_python_parser 的纯 Rust 解析器),语义分析在 crates/ruff_python_semantic 中以作用域模型(scope/binding/reference)支撑跨语句规则(如未使用变量、未使用导入);
- 内置缓存:crates/ruff_cache 维护基于文件内容与 mtime 的缓存键(见 cache_key.rs),未变更文件直接跳过分析,这正是 README "built-in caching, to avoid re-analyzing unchanged files" 的落地;
- 格式化器继承成熟的 Rust 格式引擎:README 致谢一节明确说明,formatter 构建自 Rome 项目
rome_formatter的分支,并吸收了 Rome、Prettier、Black 的 API 与实现细节;核心引擎位于 crates/ruff_formatter。与 Black 的行为对齐细节可参考 docs/formatter/black.md; - 导入解析借鉴 Pyright 的算法(README Acknowledgements),对应 crates/ruff_python_importer 中的导入插入/重排逻辑;
- 基准测试常态化:crates/ruff_benchmark 提供 formatter、lexer、linter、parser、module_resolution 等 criterion 基准(benches 目录),scripts/benchmarks/ 中还包含跨工具对比脚本——README 顶部的"CPython 基准柱状图"即由此类流程产出。
八、贡献、支持与许可
- 贡献:仓库提供 CONTRIBUTING.md 与 AGENTS.md 贡献指南;新增规则可参考 scripts/add_rule.py 的自动化流程,开发工具集中在 crates/ruff_dev(文档生成、schema 生成、AST/词法打印等);
- 致谢:linter 借鉴了 Flake8、Pyflakes、pycodestyle、pydocstyle、pyupgrade、isort 的 API 与实现细节,部分为直接 Rust 移植;formatter 基于 Rome 的
rome_formatter分支;import resolver 基于 Pyright 的导入解析算法;另受 Clippy、ESLint 等生态外工具影响(原文见 README.md 的 Acknowledgements 一节); - 使用者:README 的 "Who's Using Ruff?" 一节列出了近百个采用项目,包括 Apache Airflow、FastAPI、Hugging Face、Pandas、SciPy、PyTorch、pytest、Pylint、pip 等;
- 许可:整个仓库(含 LICENSE)采用 MIT 协议;
- 维护方:Ruff 由 Astral 团队维护,同仓库内还包含类型检查器
ty系列 crate(crates/ty)与 LSP 服务 ruff_server。
九、快速上手清单
- 安装:
uv tool install ruff@latest(或pip install ruff); - 零配置起步:
ruff check使用F/E/B/UP/RUF等默认规则集; - 需要修复:
ruff check --fix; - 格式化:
ruff format(默认与 Black 对齐:88 列、双引号、magic trailing comma); - 项目级配置:在
pyproject.toml的[tool.ruff]/[tool.ruff.lint]/[tool.ruff.format]中调整,或用独立ruff.toml(可被编辑器按 ruff.schema.json 校验); - 需要最新规则/风格:开启
preview = true或--preview,但注意其不稳定性; - CI 固化:按第四节的 pre-commit 或 GitHub Action 模板接入。
以上全部命令、配置默认值与规则类别均来自 README.md,实现细节佐证来自 crates/ 下对应 crate,可按文中给出的相对路径在当前仓库中继续深入。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0623
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00