python-ruff

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Ruff — Linting and Formatting

Python Ruff — 代码检查与格式化

Ruff is an extremely fast Python linter and code formatter written in Rust. It replaces Flake8, Black, isort, pydocstyle, pyupgrade, and autoflake with a single unified tool that runs 10–100x faster than any of them individually. Ruff supports over 800 built-in rules and provides automatic fix capabilities for many violations.
Ruff是一款用Rust编写的超快速Python代码检查器与代码格式化工具,可替代Flake8、Black、isort、pydocstyle、pyupgrade和autoflake等多款工具,运行速度比其中任何一款单独使用快10-100倍。Ruff支持800+内置规则,还能自动修复许多代码违规问题。

Installation

安装

Install Ruff via pip, uv, or as a development dependency:
bash
pip install ruff
uv add --dev ruff
通过pip、uv或作为开发依赖安装Ruff:
bash
pip install ruff
uv add --dev ruff

Core Commands

核心命令

bash
ruff check                    # Lint all files in current directory
ruff check --fix              # Lint and auto-fix safe violations
ruff check --unsafe-fixes     # Show unsafe fixes (review before applying)
ruff check --fix --unsafe-fixes  # Apply all fixes including unsafe ones
ruff check --watch            # Re-lint on file changes
ruff format                   # Format all files in current directory
ruff format --check           # Check formatting without writing changes
ruff format --diff            # Show formatting diff without writing
Run both linting (with import sorting) and formatting in sequence:
bash
ruff check --select I --fix   # Sort imports first
ruff format                   # Then format
bash
ruff check                    # 检查当前目录下的所有文件
ruff check --fix              # 检查并自动修复安全的代码违规问题
ruff check --unsafe-fixes     # 显示不安全的修复方案(应用前请先审核)
ruff check --fix --unsafe-fixes  # 应用所有修复方案,包括不安全的修复
ruff check --watch            # 文件变更时自动重新检查
ruff format                   # 格式化当前目录下的所有文件
ruff format --check           # 检查格式问题但不写入修改
ruff format --diff            # 显示格式差异但不写入修改
按顺序执行代码检查(含导入排序)与格式化:
bash
ruff check --select I --fix   # 先排序导入语句
ruff format                   # 再进行格式化

Configuration

配置

Ruff reads from
pyproject.toml
,
ruff.toml
, or
.ruff.toml
. All three support the same schema;
ruff.toml
and
.ruff.toml
omit the
[tool.ruff]
prefix.
Ruff会从
pyproject.toml
ruff.toml
.ruff.toml
读取配置。这三个文件支持相同的配置结构;
ruff.toml
.ruff.toml
无需添加
[tool.ruff]
前缀。

Recommended Starter Configuration

推荐起始配置

toml
[tool.ruff]
target-version = "py312"
line-length = 88

[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "F",    # Pyflakes
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "SIM",  # flake8-simplify
    "I",    # isort
]
ignore = ["E501"]  # line-too-long (handled by formatter)

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = true
See
references/configuration-guide.md
for the full configuration reference.
toml
[tool.ruff]
target-version = "py312"
line-length = 88

[tool.ruff.lint]
select = [
    "E",    # pycodestyle错误
    "F",    # Pyflakes
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "SIM",  # flake8-simplify
    "I",    # isort
]
ignore = ["E501"]  # 行过长问题(由格式化工具处理)
完整配置参考请查看
references/configuration-guide.md

Rule Selection Best Practices

规则选择最佳实践

Rule codes follow the pattern
PREFIX + digits
(e.g.,
F401
= Pyflakes unused import,
E711
= pycodestyle comparison to None).
Start small, then expand:
toml
undefined
规则代码遵循“前缀+数字”的模式(例如
F401
=Pyflakes未使用导入,
E711
=pycodestyle与None的比较)。
从小范围开始,逐步扩展:
toml
undefined

Step 1: Minimal (safe baseline)

步骤1:最小配置(安全基线)

select = ["E4", "E7", "E9", "F"]
select = ["E4", "E7", "E9", "F"]

Step 2: Recommended expansion

步骤2:推荐扩展配置

select = ["E", "F", "UP", "B", "SIM", "I"]
select = ["E", "F", "UP", "B", "SIM", "I"]

Step 3: Strict (with targeted ignores)

步骤3:严格配置(需精心筛选忽略规则)

select = ["ALL"] ignore = ["D", "ANN", "COM812", "ISC001"]

**Key rule prefixes:**

| Prefix | Source             | Purpose                        |
|--------|--------------------|--------------------------------|
| `E/W`  | pycodestyle        | Style errors and warnings      |
| `F`    | Pyflakes           | Logical errors, unused imports |
| `B`    | flake8-bugbear     | Likely bugs and design issues  |
| `UP`   | pyupgrade          | Upgrade to modern Python syntax|
| `SIM`  | flake8-simplify    | Code simplification            |
| `I`    | isort              | Import sorting                 |
| `N`    | pep8-naming        | Naming convention checks       |
| `D`    | pydocstyle         | Docstring conventions          |
| `ANN`  | flake8-annotations | Type annotation enforcement    |
| `S`    | flake8-bandit      | Security checks                |
| `RUF`  | Ruff-native        | Ruff-specific rules            |

Use `lint.select` (not `lint.extend-select`) to make rule sets explicit. Avoid enabling `ALL` without carefully curating an `ignore` list, as it enables new rules on every Ruff upgrade.

See `references/rule-categories.md` for detailed rule guidance and common ignores.
select = ["ALL"] ignore = ["D", "ANN", "COM812", "ISC001"]

**关键规则前缀:**

| 前缀 | 来源               | 用途                          |
|------|--------------------|-------------------------------|
| `E/W`| pycodestyle        | 样式错误与警告                |
| `F`  | Pyflakes           | 逻辑错误、未使用导入          |
| `B`  | flake8-bugbear     | 潜在bug与设计问题             |
| `UP` | pyupgrade          | 升级至现代Python语法          |
| `SIM`| flake8-simplify    | 代码简化                      |
| `I`  | isort              | 导入排序                      |
| `N`  | pep8-naming        | 命名规范检查                  |
| `D`  | pydocstyle         | 文档字符串规范                |
| `ANN`| flake8-annotations | 类型注解强制检查              |
| `S`  | flake8-bandit      | 安全检查                      |
| `RUF`| Ruff原生           | Ruff专属规则                  |

使用`lint.select`(而非`lint.extend-select`)来明确规则集。在未精心筛选`ignore`列表的情况下,请勿启用`ALL`,因为Ruff每次升级都会新增规则。

详细规则指导与常见忽略规则请查看`references/rule-categories.md`。

Automatic Fixes

自动修复

Ruff distinguishes between safe and unsafe fixes:
  • Safe fixes preserve code behavior exactly — applied by default with
    --fix
  • Unsafe fixes may change runtime behavior (e.g., exception types, removed comments) — opt-in with
    --unsafe-fixes
Promote or demote fix safety per rule:
toml
[tool.ruff.lint]
extend-safe-fixes = ["UP"]    # Treat pyupgrade fixes as safe
extend-unsafe-fixes = ["B"]   # Require explicit opt-in for bugbear fixes
Disable auto-fix for specific rules while keeping them as violations:
toml
[tool.ruff.lint]
fixable = ["ALL"]
unfixable = ["F401"]  # Flag unused imports but don't auto-remove them
Ruff区分安全修复不安全修复
  • 安全修复:完全保留代码行为——使用
    --fix
    时默认应用
  • 不安全修复:可能改变运行时行为(例如异常类型、移除注释)——需通过
    --unsafe-fixes
    手动启用
可按规则调整修复的安全级别:
toml
[tool.ruff.lint]
extend-safe-fixes = ["UP"]    # 将pyupgrade修复视为安全修复
extend-unsafe-fixes = ["B"]   # 对bugbear修复需手动启用
禁用特定规则的自动修复,但仍将其标记为违规:
toml
[tool.ruff.lint]
fixable = ["ALL"]
unfixable = ["F401"]  # 标记未使用导入但不自动移除

Error Suppression

错误抑制

Line-level suppression

行级抑制

python
import os  # noqa: F401
x = 1  # noqa: E741, F841   # suppress multiple rules
y = 1  # noqa                # suppress all (avoid — too broad)
python
import os  # noqa: F401
x = 1  # noqa: E741, F841   # 抑制多个规则
y = 1  # noqa                # 抑制所有规则(不推荐——范围过广)

Block-level suppression (preferred over blanket noqa)

块级抑制(优于全局noqa)

python
undefined
python
undefined

ruff: disable[E501]

ruff: disable[E501]

LONG_CONSTANT_1 = "Lorem ipsum dolor sit amet, consectetur adipiscing..." LONG_CONSTANT_2 = "Lorem ipsum dolor sit amet, consectetur adipiscing..."
LONG_CONSTANT_1 = "Lorem ipsum dolor sit amet, consectetur adipiscing..." LONG_CONSTANT_2 = "Lorem ipsum dolor sit amet, consectetur adipiscing..."

ruff: enable[E501]

ruff: enable[E501]

undefined
undefined

File-level suppression

文件级抑制

python
undefined
python
undefined

ruff: noqa: F841 # suppress specific rule for entire file

ruff: noqa: F841 # 抑制整个文件的特定规则

ruff: noqa # suppress all (avoid — use per-file-ignores instead)

ruff: noqa # 抑制所有规则(不推荐——改用per-file-ignores)

undefined
undefined

Per-file ignores in config (preferred)

配置文件中的按文件忽略(推荐)

toml
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]          # re-exports are intentional
"tests/**/*.py" = ["S101", "ANN"] # asserts and no annotations in tests
"scripts/**/*.py" = ["T20"]       # print() allowed in scripts
toml
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]          # 重导出为有意设计
"tests/**/*.py" = ["S101", "ANN"] # 测试文件允许使用断言与无类型注解
"scripts/**/*.py" = ["T20"]       # 脚本文件允许使用print()

Detecting unused suppressions

检测未使用的抑制标记

bash
ruff check --extend-select RUF100        # flag stale noqa comments
ruff check --extend-select RUF100 --fix  # auto-remove stale noqa
bash
ruff check --extend-select RUF100        # 标记过时的noqa注释
ruff check --extend-select RUF100 --fix  # 自动移除过时的noqa注释

Formatter Configuration

格式化工具配置

The Ruff formatter is a drop-in replacement for Black. Key options:
toml
[tool.ruff.format]
quote-style = "double"            # "double" | "single" | "preserve"
indent-style = "space"            # "space" | "tab"
line-ending = "auto"              # "auto" | "lf" | "crlf" | "native"
skip-magic-trailing-comma = false # respect trailing commas (like Black)
docstring-code-format = true      # format code examples in docstrings
Ruff格式化工具可直接替代Black。关键配置选项:
toml
[tool.ruff.format]
quote-style = "double"            # "double" | "single" | "preserve"
indent-style = "space"            # "space" | "tab"
line-ending = "auto"              # "auto" | "lf" | "crlf" | "native"
skip-magic-trailing-comma = false # 保留尾随逗号(与Black一致)
docstring-code-format = true      # 格式化文档字符串中的代码示例

Suppressing formatter

禁用格式化

python
undefined
python
undefined

fmt: off

fmt: off

matrix = [1,0,0, 0,1,0, 0,0,1]
matrix = [1,0,0, 0,1,0, 0,0,1]

fmt: on

fmt: on

result = some_call() # fmt: skip
undefined
result = some_call() # fmt: skip
undefined

Rules incompatible with the formatter

与格式化工具冲突的规则

Disable these rules to avoid conflicts when using
ruff format
:
toml
[tool.ruff.lint]
ignore = [
    "W191",   # tab-indentation
    "E111",   # indentation-with-invalid-multiple
    "COM812", # missing-trailing-comma
    "ISC002", # multi-line-implicit-string-concatenation
    "Q000",   # bad-quotes-inline-string
    "Q001",   # bad-quotes-multiline-string
    "Q002",   # bad-quotes-docstring
]
使用
ruff format
时,需禁用以下规则以避免冲突:
toml
[tool.ruff.lint]
ignore = [
    "W191",   # 制表符缩进
    "E111",   # 无效倍数缩进
    "COM812", # 缺少尾随逗号
    "ISC002", # 多行隐式字符串拼接
    "Q000",   # 行内字符串引号格式错误
    "Q001",   # 多行字符串引号格式错误
    "Q002",   # 文档字符串引号格式错误
]

CI and Pre-commit Integration

CI与预提交集成

GitHub Actions

GitHub Actions

yaml
- name: Lint and format check
  run: |
    ruff check .
    ruff format --check .
yaml
- name: Lint and format check
  run: |
    ruff check .
    ruff format --check .

pre-commit hooks

pre-commit钩子

yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.9.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format
yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.9.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

Migrating an existing codebase

迁移现有代码库

Auto-add
noqa
directives to all current violations, then clean up incrementally:
bash
ruff check --add-noqa .    # adds noqa to all failing lines
ruff check --extend-select RUF100 --fix .  # remove stale noqa over time
自动为所有当前违规代码添加
noqa
指令,然后逐步清理:
bash
ruff check --add-noqa .    # 为所有违规行添加noqa
ruff check --extend-select RUF100 --fix .  # 逐步移除过时的noqa

Quick Reference

快速参考

TaskCommand
Lint current directory
ruff check
Lint and fix safe violations
ruff check --fix
Format current directory
ruff format
Check formatting (CI mode)
ruff format --check
Sort imports only
ruff check --select I --fix
Explain a rule
ruff rule F401
List all rules
ruff linter
Show active config for a file
ruff check --show-settings <file.py>
Flag unused noqa comments
ruff check --extend-select RUF100
任务命令
检查当前目录
ruff check
检查并修复安全违规问题
ruff check --fix
格式化当前目录
ruff format
检查格式(CI模式)
ruff format --check
仅排序导入语句
ruff check --select I --fix
查看规则说明
ruff rule F401
列出所有规则
ruff linter
显示文件的生效配置
ruff check --show-settings <file.py>
标记未使用的noqa注释
ruff check --extend-select RUF100

Additional Resources

额外资源

Reference Files

参考文件

  • references/rule-categories.md
    — Detailed rule prefixes, common ignores, and per-category guidance
  • references/configuration-guide.md
    — Full configuration options for linter and formatter
  • references/rule-categories.md
    — 详细的规则前缀、常见忽略规则与分类指导
  • references/configuration-guide.md
    — 代码检查器与格式化工具的完整配置选项

Example Files

示例文件

  • examples/pyproject.toml
    — Production-ready pyproject.toml configuration
  • examples/ruff.toml
    — Standalone ruff.toml configuration (monorepo root)
  • examples/pre-commit-config.yaml
    — pre-commit hooks configuration
  • examples/pyproject.toml
    — 生产环境可用的pyproject.toml配置
  • examples/ruff.toml
    — 独立的ruff.toml配置(单体仓库根目录)
  • examples/pre-commit-config.yaml
    — pre-commit钩子配置