Ruff

← 返回目录 > ← 返回总览

相关工具推荐

工具 说明
Mypy Python 静态类型检查工具,与 Ruff 互补
Pylint Python 代码质量检查工具,包含部分 Ruff 未覆盖的检查
Bandit Python 代码安全扫描工具,Ruff 内置 flake8-bandit 兼容规则
Pre-commit 多语言 Git 钩子管理框架,Ruff 的主流集成方式之一

1. 简介

Ruff 是由 Astral 开发的一款用 Rust 编写的极速 Python 代码检查器(Linter)和格式化工具(Formatter)。它将代码检查和格式化功能融为一体,旨在以单一工具替代 Flake8、Black、isort、pydocstyle、pyupgrade、autoflake 等数十个传统 Python 代码质量工具。

  • 主要检查语言:Python
  • 主要检查能力:代码检查、代码格式化、Import 排序、安全检查;涵盖代码质量检查 + 代码格式化
  • 核心检查原理:Rust 实现的原生解析器(基于 LibCST),单进程内完成检查和格式化
  • 检查规则/选项:900+ 条内置 lint 规则(整合 Flake8、isort、pyupgrade、Pylint 等数十个插件的规则,按 50+ 个规则类别组织),全量规则列表
  • GitHub 仓库https://github.com/astral-sh/ruff(47,943 stars)
  • 开源协议:MIT / Apache 2.0(Ruff 核心和插件分别授权)
  • 最新稳定版本:0.11.5
  • 运行环境要求:无(独立二进制,提供预编译二进制和 wheel 包)
  • 误报率:低

2. 官方文档

资源 链接
官方文档首页 https://docs.astral.sh/ruff/
快速入门教程 https://docs.astral.sh/ruff/tutorial/
配置选项完整文档 https://docs.astral.sh/ruff/configuration/
所有设置项参考 https://docs.astral.sh/ruff/settings/
所有规则文档 https://docs.astral.sh/ruff/rules/
Linter 文档(含告警抑制) https://docs.astral.sh/ruff/linter/
格式化器文档 https://docs.astral.sh/ruff/formatter/
编辑器集成文档 https://docs.astral.sh/ruff/editors/
集成方式文档(CI/CD/pre-commit) https://docs.astral.sh/ruff/integrations/
Preview 模式说明 https://docs.astral.sh/ruff/preview/
FAQ https://docs.astral.sh/ruff/faq/
在线 Playground https://play.ruff.rs/
GitHub 仓库 https://github.com/astral-sh/ruff
PyPI 页面 https://pypi.org/project/ruff/

3. 社区优秀实践

3.1 FastAPI

FastAPI 是 Python 生态中最流行的 Web 框架之一,已全面采用 Ruff 进行代码检查和格式化。FastAPI 在 pyproject.toml 中配置了完整的 Ruff 规则集,涵盖代码检查、import 排序等。

FastAPI 的实践特点:

  • 启用了 EWFI(isort)、B(flake8-bugbear)、C4(flake8-comprehensions)、UP(pyupgrade)规则集
  • 通过 per-file-ignores__init__.py 和文档示例文件放宽了部分规则
  • 配置了 lint.isort.known-third-party 指定第三方包,优化 import 排序

3.2 Pandas

Pandas 是数据分析领域最广泛使用的 Python 库之一,已将代码检查工具迁移至 Ruff。作为一个拥有数十万行代码的大型项目,Pandas 特别受益于 Ruff 的极速检查能力。

Pandas 的实践特点:

  • 启用了广泛的规则集,包括 FEWYTTBQT10INTPL(Pylint)、PT(flake8-pytest-style)、PIEPYITIDISCTCC4PGHRUFS102NPY002PERFFLYGFAICN001SLOTRSE
  • 配置了 per-file-ignoresasv_bench/*pandas/tests/*pandas/_typing.py 进行差异化规则管理
  • 利用 flake8-tidy-imports.banned-api 禁止直接使用 urllib.request.urlopennumpy.testing 等内部 API
  • 启用了 format.docstring-code-format = true,自动格式化 docstring 中的代码示例

3.3 pytest

pytest 是 Python 测试领域的主流框架,已采用 Ruff 作为其代码质量保障工具。pytest 项目通过 Ruff 统一管理代码风格、import 排序和文档字符串检查。

pytest 的实践特点:

  • 启用了 B(flake8-bugbear)、D(pydocstyle)、EFI(isort)、PLC/PLE/PLR/PLW(Pylint 子集)、PYIRUFUP(pyupgrade)、W 等规则集
  • 配置了 pydocstyle.convention = "pep257" 统一文档字符串风格
  • testing/**/*.py 目录配置了特定的 per-file-ignores,放宽测试代码的部分规则
  • 使用 isort.required-imports 强制每个文件包含 from __future__ import annotations

3.4 Apache Airflow

Apache Airflow 是最流行的开源工作流编排平台之一,拥有庞大的代码库。Airflow 不仅使用 Ruff 进行通用代码检查,还启用了 Ruff 内置的 Airflow 专用规则集(AIR)。

Airflow 的实践特点:

  • 启用了 Ruff 的 Airflow 专用规则(AIR),检测 DAG 配置问题和 Airflow 3.0 迁移兼容性
  • 在 pre-commit 和 CI/CD 中同时集成 Ruff 检查和格式化
  • 作为大型 Monorepo 项目,充分利用了 Ruff 的级联配置和缓存机制

4. 工具配置说明

以下提供三个层级的推荐配置,适用于不同类型的项目。

4.1 配置文件说明

Ruff 支持三种配置文件格式,按优先级从高到低。Ruff 采用类似 ESLint 的层级配置策略,对每个文件使用其目录树中"最近"的配置文件。同级目录下 .ruff.toml > ruff.toml > pyproject.toml

配置文件 格式 用途
.ruff.toml TOML 项目级隐藏配置文件(最高优先级)
ruff.toml TOML 标准项目配置文件
pyproject.toml[tool.ruff] 节) TOML Python 生态标准配置文件(推荐)

配置继承:通过 extend 字段继承父级配置:

# subproject/ruff.toml
extend = "../pyproject.toml"
line-length = 100

完整配置选项文档:https://docs.astral.sh/ruff/settings/

4.2 配置文件详解

Ruff 配置文件按节组织,主要节包括 [tool.ruff](全局)、[tool.ruff.lint](规则选择)、[tool.ruff.lint.per-file-ignores](按文件忽略)、[tool.ruff.lint.isort] 等子规则集配置、[tool.ruff.format](格式化)。

配置项说明

配置项 类型 说明
[tool.ruff] target-version string 目标 Python 版本,如 "py310"
[tool.ruff] line-length int 最大行长度
[tool.ruff] extend string 继承的父级配置文件路径
[tool.ruff.lint] select string[] 启用的规则前缀列表(如 E4FIUPBSIMRUFNANNSC4DTZERAFASTPERF
[tool.ruff.lint] ignore string[] 忽略的规则 ID 列表
[tool.ruff.lint.per-file-ignores] map 按文件忽略规则,键为 glob,值为规则 ID 列表
[tool.ruff.lint.isort] known-first-party string[] 一方包列表
[tool.ruff.lint.isort] combine-as-imports bool 合并 from x import (a, b) 形式
[tool.ruff.lint.isort] split-on-trailing-comma bool 是否在尾随逗号处换行
[tool.ruff.lint.flake8-annotations] mypy-init-return bool __init__ 返回类型注解是否要求
[tool.ruff.lint.flake8-annotations] suppress-none-returning bool 是否抑制返回 None 的函数的返回值注解告警
[tool.ruff.format] quote-style string 引号风格:double/single/preserve
[tool.ruff.format] indent-style string 缩进风格:space/tab
[tool.ruff.format] docstring-code-format bool 是否格式化文档字符串中的代码片段

推荐配置示例(基础配置,适合新项目/个人项目)

零配置即可使用,以下为推荐的最低配置:

# pyproject.toml
[tool.ruff]
target-version = "py310"
line-length = 88

[tool.ruff.lint]
select = [
    "E4",   # pycodestyle errors(默认启用)
    "E7",   # pycodestyle errors(默认启用)
    "E9",   # pycodestyle errors(默认启用)
    "F",    # Pyflakes(默认启用)
    "I",    # isort -- import 排序,确保 import 语句有序
    "UP",   # pyupgrade -- 提示使用新版 Python 语法
]
ignore = [
    "E501", # 行长度限制(由 formatter 处理)
]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"

规则说明

规则 来源 说明
E4 pycodestyle 导入和模块级错误(如 E402 import 不在顶部)
E7 pycodestyle 语句级错误(如比较错误 E711/E712)
E9 pycodestyle 运行时错误(如 SyntaxError、IndexError)
F Pyflakes 未使用导入/变量、重复定义等基础错误
I isort import 语句排序和分组
UP pyupgrade 推荐使用新版 Python 语法(如 Optional[X] -> X | None

推荐配置示例(标准配置,适合团队项目/中型项目)

在基础配置之上增加 bug 检测和代码简化规则:

# pyproject.toml
[tool.ruff]
target-version = "py310"
line-length = 88

[tool.ruff.lint]
select = [
    # ---- 默认规则 ----
    "E4",   # pycodestyle errors
    "E7",   # pycodestyle errors
    "E9",   # pycodestyle errors
    "F",    # Pyflakes
    # ---- 推荐扩展 ----
    "I",    # isort -- import 排序
    "UP",   # pyupgrade -- Python 语法升级
    "B",    # flake8-bugbear -- 常见 bug 和代码陷阱检测
    "SIM",  # flake8-simplify -- 代码简化建议
    "RUF",  # Ruff 专用规则集
]
ignore = [
    "E501",   # 行长度限制(由 formatter 处理)
    "B008",   # 允许函数调用作为默认参数(FastAPI Depends 常用)
]

# 按文件忽略规则
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]    # __init__.py 中允许未使用导入(re-export)
"tests/*" = ["S101"]         # 测试文件中允许使用 assert

# isort 配置
[tool.ruff.lint.isort]
known-first-party = ["myproject"]
combine-as-imports = true

[tool.ruff.format]
quote-style = "double"
indent-style = "space"

新增规则说明

规则 来源 说明
B flake8-bugbear 检测常见 bug(如可变默认参数 B006、未使用循环变量 B007、函数中使用循环变量 B023)
SIM flake8-simplify 代码简化建议(如使用 dict.get 代替 if-else、简化条件表达式)
RUF Ruff 专用 Ruff 社区规则(如未使用的 noqa 注释 RUF100、无效 pyproject 配置等)

推荐配置示例(严格配置,适合高质量项目/库项目)

在标准配置之上增加类型注解、命名规范、文档字符串和安全检查:

# pyproject.toml
[tool.ruff]
target-version = "py310"
line-length = 88

[tool.ruff.lint]
select = [
    # ---- 默认规则 ----
    "E4",   # pycodestyle errors
    "E7",   # pycodestyle errors
    "E9",   # pycodestyle errors
    "F",    # Pyflakes
    # ---- 推荐扩展 ----
    "I",    # isort -- import 排序
    "UP",   # pyupgrade -- Python 语法升级
    "B",    # flake8-bugbear -- 常见 bug 检测
    "SIM",  # flake8-simplify -- 代码简化
    "RUF",  # Ruff 专用规则
    # ---- 严格扩展 ----
    "N",    # pep8-naming -- PEP 8 命名规范
    "ANN",  # flake8-annotations -- 类型注解检查
    "S",    # flake8-bandit -- 安全问题检测
    "C4",   # flake8-comprehensions -- 更好的推导式写法
    "DTZ",  # flake8-datetimez -- 时区感知的 datetime 使用
    "ERA",  # eradicate -- 检测注释掉的代码
    "FAST", # FastAPI 专用规则
    "PERF", # Perflint -- 性能问题检测
]
ignore = [
    "E501",   # 行长度限制(由 formatter 处理)
    "S101",   # 允许使用 assert(测试代码中常用)
    "B008",   # 允许函数调用作为默认参数(FastAPI Depends 常用)
]

# 按文件忽略规则
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]              # re-export
"tests/*" = ["S101", "ANN", "ARG"]    # 测试文件放宽
"scripts/*" = ["S101", "ANN"]         # 脚本文件放宽
"*.ipynb" = ["T20", "E501", "ANN"]    # Notebook 放宽

# isort 配置
[tool.ruff.lint.isort]
known-first-party = ["myproject"]
combine-as-imports = true
split-on-trailing-comma = false

# flake8-annotations 配置
[tool.ruff.lint.flake8-annotations]
mypy-init-return = true
suppress-none-returning = true

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = true

新增规则说明

规则 来源 说明
N pep8-naming 检查命名是否符合 PEP 8(如类名大驼峰、函数名小写+下划线)
ANN flake8-annotations 检查函数/方法是否缺少类型注解(参数和返回值)
S flake8-bandit 安全问题检测(如硬编码密码 S105、不安全的 YAML 加载 S506、SQL 注入 S608)
C4 flake8-comprehensions 推荐更简洁的推导式写法(如用字典推导式代替 for 循环创建字典)
DTZ flake8-datetimez 检测不使用时区的 datetime 操作(避免时区相关的 bug)
ERA eradicate 检测注释掉的代码(应删除而非注释)
FAST FastAPI FastAPI 框架专用规则(如冗余 response_model FAST001)
PERF Perflint 性能问题检测(如不必要的列表推导 PERF401)

5. 主流集成方式

以下集成示例均使用 Ruff 最新稳定版本 0.15.17(截至 2026 年 6 月)。安装时建议使用 pip install ruff 获取最新版本。

5.1 pre-commit 集成(本地提交门禁)

Ruff 在 Python 社区中广泛通过 pre-commit 作为本地提交门禁使用。官方提供了专用的 pre-commit 仓库 astral-sh/ruff-pre-commit

在项目根目录创建 .pre-commit-config.yaml 文件:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    # Ruff 版本
    rev: v0.15.17
    hooks:
      # 运行 Linter 检查
      - id: ruff-check
        args: [--fix]
      # 运行格式化
      - id: ruff-format

依赖来源与执行环境说明

  • ruff-pre-commit 仓库会自动下载对应版本的 Ruff 独立二进制文件,无需本地安装 Python 包或 Rust 工具链
  • pre-commit 框架默认仅将暂存区(staged)中的变更文件传给 hook,天然实现文件级增量检查
  • 当使用 --fix 时,ruff-check 钩子应放在 ruff-format 钩子之前,因为修复可能产生需要重新格式化的代码变更

安装 pre-commit 钩子:

# 安装 pre-commit
pip install pre-commit

# 在当前仓库安装 git hooks
pre-commit install

# 手动对所有文件运行一次
pre-commit run --all-files

如果不需要处理 Jupyter Notebook,可通过 types_or 限制文件类型:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.15.17
    hooks:
      - id: ruff-check
        types_or: [python, pyi]
        args: [--fix]
      - id: ruff-format
        types_or: [python, pyi]

官方 pre-commit 集成文档:https://docs.astral.sh/ruff/integrations/#pre-commit

增量检查:pre-commit 框架默认仅把暂存区中变更文件传给 hook,天然实现文件级增量检查。上述 .pre-commit-config.yaml 配置(ruff-check + ruff-format)在 git commit 时自动只对暂存区文件运行 Ruff。

5.2 IDE 集成

VS Code

安装官方扩展 Ruff(扩展 ID:charliermarsh.ruff)。建议使用扩展版本 2024.32.0 或更高以获得最佳体验。

.vscode/settings.json 中推荐配置:

{
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll.ruff": "explicit",
      "source.organizeImports.ruff": "explicit"
    }
  }
}

VS Code 扩展仓库:https://github.com/astral-sh/ruff-vscode

编辑器集成文档:https://docs.astral.sh/ruff/editors/setup/#vs-code

PyCharm

PyCharm 2025.3+ 原生支持 Ruff:

  1. 打开 Settings > Python > Tools > Ruff,勾选 Enable
  2. 选择执行模式(Interpreter 或 Path),指定 Ruff 可执行文件路径
  3. 选择需要启用的选项(Linter、Formatter、Organize Imports)

PyCharm 集成文档:https://docs.astral.sh/ruff/editors/setup/#pycharm

Neovim

Ruff 内置 Language Server(ruff server),可通过 Neovim 的 LSP 客户端直接集成:

-- Neovim 0.11+ 配置示例(无需外部依赖)
---@type vim.lsp.Config
return {
  cmd = { 'ruff', 'server' },
  filetypes = { 'python' },
  root_markers = { 'pyproject.toml', 'ruff.toml', '.ruff.toml', '.git' },
  init_options = {
    settings = {
      -- Ruff language server settings
    }
  }
}

启用服务器:

vim.lsp.enable('ruff')

Neovim 集成文档:https://docs.astral.sh/ruff/editors/setup/#neovim

5.3 命令行使用方式

# 检查当前目录所有 Python 文件
ruff check .

# 检查并自动修复可修复的问题
ruff check --fix .

# 检查并显示所有可修复项(包括不安全修复)
ruff check --fix --unsafe-fixes --show-fixes .

# 仅检查指定路径
ruff check src/
ruff check path/to/file.py

# 格式化代码
ruff format .

# 检查格式(不修改文件,用于 CI)
ruff format --check .

# 查看格式化差异
ruff format --diff .

# 监听模式,文件变化时自动重新检查
ruff check --watch

# 指定配置文件
ruff check --config path/to/ruff.toml .

# 查看特定规则的说明
ruff rule E501

# 查看当前配置
ruff check --show-settings path/to/file.py

# 查看将检查的文件列表
ruff check --show-files .

# 清除缓存
ruff clean

# 启动 Language Server
ruff server

# 查看版本
ruff version

增量检查(原生缓存机制):Ruff 内置缓存机制(.ruff_cache),默认启用,无需额外配置,自动跳过未更改文件的重复分析。

# 默认启用缓存,跳过未更改文件
ruff check .

# 禁用缓存
ruff check --no-cache .

# 指定缓存目录
ruff check --cache-dir /path/to/cache .

# 清除缓存
ruff clean

增量检查(基于 Git 的文件列表):通过 Git diff 获取变更文件列表,仅对变更的 Python 文件运行 Ruff。

# 只检查相对于 HEAD 变更的 Python 文件(新增、修改、重命名)
ruff check $(git diff --name-only --diff-filter=ACMR HEAD -- '*.py')

# 只检查暂存区的文件
ruff check $(git diff --name-only --cached -- '*.py')

# 只检查指定分支之间的差异文件
ruff check $(git diff --name-only main...HEAD -- '*.py')

CI 脚本调用

GitHub Actions(手动安装)

# .github/workflows/ci.yml
name: CI
on: push
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Install dependencies
        run: pip install ruff
      - name: Run Ruff
        run: ruff check --output-format=github .
      - name: Check formatting
        run: ruff format --check .

官方 GitHub Actions 集成文档:https://docs.astral.sh/ruff/integrations/#github-actions

GitLab CI

# .gitlab-ci.yml
.base_ruff:
  stage: build
  interruptible: true
  image:
    name: ghcr.io/astral-sh/ruff:0.15.17-alpine
  before_script:
    - cd $CI_PROJECT_DIR
    - ruff --version

Ruff Check:
  extends: .base_ruff
  script:
    - ruff check --output-format=gitlab --output-file=code-quality-report.json
  artifacts:
    reports:
      codequality: $CI_PROJECT_DIR/code-quality-report.json

Ruff Format:
  extends: .base_ruff
  script:
    - ruff format --diff

官方 GitLab CI 集成文档:https://docs.astral.sh/ruff/integrations/#gitlab-cicd

增量检查:在 CI/CD 中可通过 Git diff 获取 PR/MR 变更文件列表,仅对变更的 Python 文件运行 Ruff。

GitHub Actions 中按 PR 变更文件触发增量检查

# .github/workflows/ruff.yml
name: Ruff
on:
  pull_request:
    branches: [main]
jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: astral-sh/ruff-action@v3
        with:
          args: "check --output-format=github $(git diff --name-only --diff-filter=ACMR origin/main... -- '*.py')"

GitLab CI 中按 MR 变更文件触发增量检查

# .gitlab-ci.yml
Ruff Check (Incremental):
  stage: build
  image: ghcr.io/astral-sh/ruff:0.15.17-alpine
  script:
    - ruff check --output-format=gitlab --output-file=code-quality-report.json $(git diff --name-only --diff-filter=ACMR origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME... -- '*.py')
  artifacts:
    reports:
      codequality: $CI_PROJECT_DIR/code-quality-report.json
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

5.4 GitHub Action 插件

# .github/workflows/ruff.yml
name: Ruff
on: [push, pull_request]
jobs:
  ruff:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/ruff-action@v3
        with:
          version: "0.15.17"
          args: "check --output-format=github"

ruff-action 仓库:https://github.com/astral-sh/ruff-action

5.5 Python 生态主流安装方式

pip 安装

pip install ruff

uv 安装(推荐现代项目使用)

# 添加为项目开发依赖
uv add --dev ruff

# 或全局安装
uv tool install ruff

pyproject.toml 声明为开发依赖

[project]
name = "my-project"
version = "0.1.0"
requires-python = ">=3.10"

[project.optional-dependencies]
dev = [
    "ruff>=0.15.0",
]

安装:

pip install -e ".[dev]"

官方安装文档:https://docs.astral.sh/ruff/installation/

6. 告警抑制(屏蔽)方法

6.1 通过代码注释屏蔽

行级 # noqa 注释

在代码行末尾添加 # noqa 注释来屏蔽特定规则或所有规则:

# 屏蔽特定规则
x = 1  # noqa: F841

# 屏蔽多个规则
import os  # noqa: E501, F401

# 屏蔽该行所有规则
y = 2  # noqa

对于多行语句,可在首行上方使用 # ruff: ignore 注释覆盖整个逻辑行:

# ruff: ignore[E501]  # 覆盖整个列表字面量
things = [
    "really long string literal ...",
    "really long string literal ...",
]

官方文档:行级抑制说明

块级 # ruff: disable / # ruff: enable 注释

使用 disable/enable 注释对屏蔽一个代码块中的规则:

# ruff: disable[E501]
VALUE_1 = "Lorem ipsum dolor sit amet ..."
VALUE_2 = "Lorem ipsum dolor sit amet ..."
VALUE_3 = "Lorem ipsum dolor sit amet ..."
# ruff: enable[E501]

也可以在函数体内使用:

def foo():
    # ruff: disable[E741, F841]
    i = 1
    # ruff: enable[E741, F841]

如果没有匹配的 enable 注释,Ruff 会将其视为隐式范围,直到遇到缩进级别更低的代码为止。建议始终使用显式范围抑制。

官方文档:块级抑制说明

文件级 # ruff: noqa 注释

在文件顶部添加注释来屏蔽整个文件的特定规则或所有规则:

# ruff: noqa: F401, E501
# 屏蔽整个文件的 F401 和 E501 规则

# ruff: noqa
# 屏蔽整个文件的所有规则

官方文档:文件级抑制说明

6.2 通过工具配置文件屏蔽

lint.ignore -- 全局规则屏蔽

在配置文件中全局屏蔽特定规则:

# pyproject.toml
[tool.ruff.lint]
ignore = [
    "E501",   # 行长度限制(由 formatter 处理)
    "S101",   # 允许使用 assert
    "ANN001", # 允许函数参数缺少类型注解
]

官方文档:lint.ignore 设置

lint.per-file-ignores -- 按文件/目录屏蔽

在配置文件中按文件模式屏蔽特定规则:

# pyproject.toml
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]              # __init__.py 中允许未使用导入
"tests/*" = ["S101", "ANN"]           # 测试文件中允许 assert 和缺少类型注解
"**/{tests,docs,tools}/*" = ["E402"]  # 特定目录中允许 import 不在顶部
"*.ipynb" = ["T20"]                   # Notebook 中允许 print 语句
"migrations/*" = ["ALL"]              # 迁移文件跳过所有检查

官方文档:per-file-ignores 设置

exclude / extend-exclude -- 排除文件/目录

在配置文件中排除特定文件或目录,使其不被检查和格式化:

# pyproject.toml
[tool.ruff]
# 排除目录(覆盖默认排除列表中的项)
exclude = [
    ".git",
    ".venv",
    "build",
    "dist",
]

# 额外排除(在默认排除基础上追加)
extend-exclude = [
    "migrations/",
    "vendor/",
    "generated/",
]

官方文档:exclude 设置

官方文档:extend-exclude 设置

6.3 通过工具命令行参数屏蔽

通过命令行参数临时覆盖配置:

# 屏蔽指定规则
ruff check --ignore E501 --ignore S101 .

# 只启用指定规则
ruff check --select E,F .

# 排除文件/目录
ruff check --exclude migrations/ .

# 按文件忽略规则
ruff check --per-file-ignores '{"tests/*": ["S101"]}' .

# 忽略所有 noqa 注释(用于排查)
ruff check --ignore-noqa .

官方文档:命令行接口说明

6.4 通过集成调度工具屏蔽

pre-commit 的文件匹配

.pre-commit-config.yaml 中,可通过 hook 级别的 filesexcludetypestypes_orexclude_types 控制检查范围:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.15.17
    hooks:
      - id: ruff-check
        args: [--fix]
        # 仅检查 Python 和 PYI 文件,排除 Jupyter Notebook
        types_or: [python, pyi]
        # 排除特定目录
        exclude: ^vendor/

pre-commit 顶层配置也可控制行为:

# 顶层配置示例
default_stages: [commit] # 默认在 commit 阶段运行
fail_fast: false # 不因第一个失败就停止

官方文档:pre-commit 集成说明

6.5 --add-noqa 自动添加 noqa

Ruff 提供了自动添加 noqa 指令的功能:

# 自动为所有报错行添加 noqa 注释
ruff check --add-noqa .

# 添加 noqa 并附上原因说明
ruff check --add-noqa="TODO: fix this later" .

官方文档:插入必要的抑制注释