首页
/ Ruff 深度实战指南:Rust 打造的高速 Python 代码检查器与格式化工具

Ruff 深度实战指南:Rust 打造的高速 Python 代码检查器与格式化工具

2026-09-05 19:04:48作者:沈韬淼Beryl

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_astcrates/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.rscheckformat 子命令的行为集成测试位于 crates/ruff/tests/integration_test.rscrates/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.tomlruff.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: falsefix_only: false:自动修复默认关闭,需显式传 --fix
  • output_formatshow_fixesunsafe_fixes 等输出与修复策略;
  • 四个嵌套子配置:linterLinterSettings)、file_resolver(含 exclude/include/respect_gitignore 等字段,见 FileResolverSettings)、formatteranalyze

仓库根目录还维护了完整的 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,规则代码(如 F401RUF015)的映射定义在 crates/ruff_linter/src/codes.rs。规则选择语法(--select F401per-file-ignores 等)在 crates/ruff_linter/src/rule_selector.rs 中实现。

七、性能与架构:从源码看 Ruff 为什么快

README 承诺的"10–100 倍速度"来自几个在源码中可验证的工程决策:

  1. 单一 Rust 二进制:解析、lint、format 共享同一次词法/语法分析结果。AST 由 crates/ruff_python_ast 提供(配合 crates/ruff_python_parser 的纯 Rust 解析器),语义分析在 crates/ruff_python_semantic 中以作用域模型(scope/binding/reference)支撑跨语句规则(如未使用变量、未使用导入);
  2. 内置缓存crates/ruff_cache 维护基于文件内容与 mtime 的缓存键(见 cache_key.rs),未变更文件直接跳过分析,这正是 README "built-in caching, to avoid re-analyzing unchanged files" 的落地;
  3. 格式化器继承成熟的 Rust 格式引擎:README 致谢一节明确说明,formatter 构建自 Rome 项目 rome_formatter 的分支,并吸收了 Rome、Prettier、Black 的 API 与实现细节;核心引擎位于 crates/ruff_formatter。与 Black 的行为对齐细节可参考 docs/formatter/black.md
  4. 导入解析借鉴 Pyright 的算法(README Acknowledgements),对应 crates/ruff_python_importer 中的导入插入/重排逻辑;
  5. 基准测试常态化crates/ruff_benchmark 提供 formatter、lexer、linter、parser、module_resolution 等 criterion 基准(benches 目录),scripts/benchmarks/ 中还包含跨工具对比脚本——README 顶部的"CPython 基准柱状图"即由此类流程产出。

八、贡献、支持与许可

  • 贡献:仓库提供 CONTRIBUTING.mdAGENTS.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

九、快速上手清单

  1. 安装:uv tool install ruff@latest(或 pip install ruff);
  2. 零配置起步:ruff check 使用 F/E/B/UP/RUF 等默认规则集;
  3. 需要修复:ruff check --fix
  4. 格式化:ruff format(默认与 Black 对齐:88 列、双引号、magic trailing comma);
  5. 项目级配置:在 pyproject.toml[tool.ruff] / [tool.ruff.lint] / [tool.ruff.format] 中调整,或用独立 ruff.toml(可被编辑器按 ruff.schema.json 校验);
  6. 需要最新规则/风格:开启 preview = true--preview,但注意其不稳定性;
  7. CI 固化:按第四节的 pre-commit 或 GitHub Action 模板接入。

以上全部命令、配置默认值与规则类别均来自 README.md,实现细节佐证来自 crates/ 下对应 crate,可按文中给出的相对路径在当前仓库中继续深入。

登录后查看全文
热门项目推荐
相关项目推荐