linting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Ruff Linting

Ruff代码检查

Ruff is an extremely fast Python linter designed as a drop-in replacement for Flake8 (plus dozens of plugins), isort, pydocstyle, pyupgrade, autoflake, and more. Written in Rust, it offers 10-100x performance improvements over traditional Python linters.
Ruff是一款极速Python代码检查工具,可直接替代Flake8(及数十个插件)、isort、pydocstyle、pyupgrade、autoflake等多款工具。它由Rust编写,性能比传统Python代码检查工具快10-100倍。

Overview

概述

Ruff provides a single CLI for linting with optional auto-fix. It supports an extensive rule set with 800+ built-in rules and integrates cleanly with pre-commit, CI systems, and modern editors.
Ruff提供单一CLI工具用于代码检查,还支持可选的自动修复功能。它拥有丰富的规则集,内置800+条规则,并且可以与pre-commit、CI系统及现代编辑器无缝集成。

Key Features

核心特性

  • Extremely Fast: 10-100x faster than Flake8, Black, isort
  • Drop-in Replacement: Compatible with existing Flake8 plugins and configurations
  • Auto-fix Support: Automatically fix many common issues
  • Comprehensive Rules: 800+ built-in rules from popular linters
  • Single Tool: Replaces flake8, isort, pyupgrade, autoflake, pydocstyle, and more
  • 极速性能:比Flake8、Black、isort快10-100倍
  • 直接替代:兼容现有Flake8插件与配置
  • 自动修复:自动修复多种常见代码问题
  • 全面规则:内置800+条来自主流检查工具的规则
  • 一站式工具:替代flake8、isort、pyupgrade、autoflake、pydocstyle等多款工具

When to Use

适用场景

  • Standardizing code quality across a project or team
  • Enforcing consistent coding rules in CI/CD pipelines
  • Replacing multiple linting tools with a single fast solution
  • Auto-fixing common code style issues
  • Migrating from Flake8, isort, or other legacy linters
  • 统一项目或团队的代码质量标准
  • 在CI/CD流水线中强制执行一致的代码规则
  • 用单一快速工具替代多款代码检查工具
  • 自动修复常见代码风格问题
  • 从Flake8、isort或其他旧版检查工具迁移

Quick Start

快速开始

bash
undefined
bash
undefined

Install Ruff

安装Ruff

uv pip install ruff
uv pip install ruff

or

pip install ruff
pip install ruff

Run linting on current directory

检查当前目录代码

ruff check .
ruff check .

Run linting with auto-fix

检查并自动修复代码

ruff check . --fix
ruff check . --fix

Watch mode for development

开发模式下实时监控

ruff check --watch
undefined
ruff check --watch
undefined

Core Patterns

核心使用模式

  1. Start minimal: Enable
    E
    and
    F
    rules first, then gradually expand
  2. Auto-fix safely: Use
    ruff check --fix
    for safe fixes only
  3. Per-file ignores: Use sparingly for generated code or special cases
  4. CI integration: Use
    ruff check --output-format github
    for GitHub Actions
  5. Single source of truth: Configure via
    pyproject.toml
    or
    ruff.toml
  1. 从简开始:先启用
    E
    F
    规则,再逐步扩展
  2. 安全修复:使用
    ruff check --fix
    仅执行安全修复
  3. 按文件忽略:仅在生成代码或特殊场景下少量使用
  4. CI集成:在GitHub Actions中使用
    ruff check --output-format github
  5. 单一配置源:通过
    pyproject.toml
    ruff.toml
    进行配置

Rule Selection

规则选择

Ruff uses a code system where each rule consists of a 1-3 letter prefix followed by digits (e.g.,
F401
). Rules are controlled via
lint.select
,
lint.extend-select
, and
lint.ignore
.
Ruff采用编码系统,每条规则由1-3个字母前缀加数字组成(例如
F401
)。可通过
lint.select
lint.extend-select
lint.ignore
控制规则。

Recommended Rule Sets

推荐规则集

Minimal (Start Here):
toml
[tool.ruff.lint]
select = ["E", "F"]  # pycodestyle errors + Pyflakes
Balanced (Recommended):
toml
[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "F",    # Pyflakes
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "SIM",  # flake8-simplify
    "I",    # isort
]
Comprehensive:
toml
[tool.ruff.lint]
select = [
    "E",    # pycodestyle errors
    "W",    # pycodestyle warnings
    "F",    # Pyflakes
    "UP",   # pyupgrade
    "B",    # flake8-bugbear
    "SIM",  # flake8-simplify
    "I",    # isort
    "N",    # pep8-naming
    "S",    # flake8-bandit (security)
    "C4",   # flake8-comprehensions
    "DTZ",  # flake8-datetimez
    "T20",  # flake8-print
    "RUF",  # Ruff-specific rules
]
ignore = ["E501"]  # Line too long (handled by formatter)
基础版(入门首选):
toml
[tool.ruff.lint]
select = ["E", "F"]  # pycodestyle错误 + Pyflakes规则
平衡版(推荐):
toml
[tool.ruff.lint]
select = [
    "E",    # pycodestyle错误
    "F",    # Pyflakes规则
    "UP",   # pyupgrade规则
    "B",    # flake8-bugbear规则
    "SIM",  # flake8-simplify规则
    "I",    # isort规则
]
完整版:
toml
[tool.ruff.lint]
select = [
    "E",    # pycodestyle错误
    "W",    # pycodestyle警告
    "F",    # Pyflakes规则
    "UP",   # pyupgrade规则
    "B",    # flake8-bugbear规则
    "SIM",  # flake8-simplify规则
    "I",    # isort规则
    "N",    # pep8-naming规则
    "S",    # flake8-bandit(安全规则)
    "C4",   # flake8-comprehensions规则
    "DTZ",  # flake8-datetimez规则
    "T20",  # flake8-print规则
    "RUF",  # Ruff专属规则
]
ignore = ["E501"]  # 忽略行过长(由格式化工具处理)

Rule Priority

规则优先级

CLI options override
pyproject.toml
, which overrides inherited configs:
  1. CLI (
    --select
    ,
    --ignore
    ) - highest priority
  2. Current
    pyproject.toml
  3. Inherited
    pyproject.toml
    files
For detailed rule configuration, see references/rule_selection.md.
CLI选项优先级高于
pyproject.toml
,后者又高于继承的配置:
  1. CLI(
    --select
    ,
    --ignore
    )- 最高优先级
  2. 当前目录的
    pyproject.toml
  3. 继承的
    pyproject.toml
    文件
如需详细规则配置,请查看references/rule_selection.md

Configuration

配置

pyproject.toml (Recommended)

pyproject.toml(推荐)

toml
[tool.ruff]
line-length = 88
target-version = "py311"
exclude = [".venv", "dist", "build", "*.pyi"]

[tool.ruff.lint]
select = ["E", "F", "UP", "B", "SIM", "I"]
ignore = ["E501"]
fixable = ["ALL"]
unfixable = []

[tool.ruff.lint.per-file-ignores]
"tests/**/*.py" = ["S101"]      # Allow assert in tests
"__init__.py" = ["F401"]         # Allow unused imports
"**/{tests,docs,tools}/*" = ["E402"]  # Allow late imports

[tool.ruff.lint.isort]
known-first-party = ["myproject"]

[tool.ruff.lint.pydocstyle]
convention = "google"
toml
[tool.ruff]
line-length = 88
target-version = "py311"
exclude = [".venv", "dist", "build", "*.pyi"]

[tool.ruff.lint]
select = ["E", "F", "UP", "B", "SIM", "I"]
ignore = ["E501"]
fixable = ["ALL"]
unfixable = []

[tool.ruff.lint.per-file-ignores]
"tests/**/*.py" = ["S101"]      # 允许在测试代码中使用assert
"__init__.py" = ["F401"]         # 允许在__init__.py中存在未使用的导入
"**/{tests,docs,tools}/*" = ["E402"]  # 允许在测试、文档、工具目录中延迟导入

[tool.ruff.lint.isort]
known-first-party = ["myproject"]

[tool.ruff.lint.pydocstyle]
convention = "google"

ruff.toml Alternative

替代方案:ruff.toml

toml
line-length = 88
target-version = "py311"

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

[lint.per-file-ignores]
"tests/**/*.py" = ["S101"]
toml
line-length = 88
target-version = "py311"

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

[lint.per-file-ignores]
"tests/**/*.py" = ["S101"]

Fix Safety

修复安全性

Ruff categorizes fixes as safe or unsafe:
TypeBehaviorDefault
SafePreserves code semanticsEnabled
UnsafeMay change runtime behaviorDisabled
bash
undefined
Ruff将修复分为安全不安全两类:
类型行为默认设置
安全保留代码语义启用
不安全可能改变代码运行行为禁用
bash
undefined

Apply only safe fixes (default)

仅执行安全修复(默认)

ruff check --fix
ruff check --fix

Apply all fixes including unsafe

执行包括不安全修复在内的所有修复

ruff check --fix --unsafe-fixes
ruff check --fix --unsafe-fixes

Show what unsafe fixes are available

查看可用的不安全修复

ruff check --unsafe-fixes
undefined
ruff check --unsafe-fixes
undefined

Adjusting Fix Safety

调整修复安全性

toml
[tool.ruff.lint]
toml
[tool.ruff.lint]

Promote unsafe fixes to safe

将不安全修复标记为安全

extend-safe-fixes = ["F601"]
extend-safe-fixes = ["F601"]

Demote safe fixes to unsafe

将安全修复标记为不安全

extend-unsafe-fixes = ["UP034"]
extend-unsafe-fixes = ["UP034"]

Control which rules can be fixed

控制哪些规则可被修复

fixable = ["ALL"] unfixable = ["F401"] # Never auto-fix unused imports

For detailed fix safety documentation, see [references/fix_safety.md](references/fix_safety.md).
fixable = ["ALL"] unfixable = ["F401"] # 从不自动修复未使用的导入

如需详细的修复安全文档,请查看[references/fix_safety.md](references/fix_safety.md)。

Error Suppression

错误忽略

Line-Level (noqa)

行级别(noqa)

python
x = 1  # noqa: F841           # Ignore specific rule
i = 1  # noqa: E741, F841     # Ignore multiple rules
x = 1  # noqa                  # Ignore all rules (avoid this)
python
x = 1  # noqa: F841           # 忽略特定规则
i = 1  # noqa: E741, F841     # 忽略多条规则
x = 1  # noqa                  # 忽略所有规则(避免使用)

File-Level

文件级别

python
undefined
python
undefined

ruff: noqa # Ignore all rules in file

ruff: noqa # 忽略当前文件所有规则

ruff: noqa: F841 # Ignore specific rule in file

ruff: noqa: F841 # 忽略当前文件的特定规则

undefined
undefined

Block-Level (Preview Mode)

块级别(预览功能)

python
undefined
python
undefined

ruff: disable[E501]

ruff: disable[E501]

VALUE_1 = "Very long string..." VALUE_2 = "Another long string..."
VALUE_1 = "Very long string..." VALUE_2 = "Another long string..."

ruff: enable[E501]

ruff: enable[E501]


For detailed suppression patterns, see [references/error_suppression.md](references/error_suppression.md).

如需详细的忽略模式,请查看[references/error_suppression.md](references/error_suppression.md)。

CLI Commands

CLI命令

bash
undefined
bash
undefined

Basic linting

基础检查

ruff check . # Lint current directory ruff check path/to/file.py # Lint specific file ruff check . --fix # Lint and auto-fix ruff check . --fix --unsafe-fixes # Include unsafe fixes
ruff check . # 检查当前目录 ruff check path/to/file.py # 检查指定文件 ruff check . --fix # 检查并自动修复 ruff check . --fix --unsafe-fixes # 包含不安全修复

Output formats

输出格式

ruff check . --output-format text # Default human-readable ruff check . --output-format github # GitHub Actions annotations ruff check . --output-format json # JSON output ruff check . --output-format sarif # SARIF format
ruff check . --output-format text # 默认人类可读格式 ruff check . --output-format github # GitHub Actions注释格式 ruff check . --output-format json # JSON格式 ruff check . --output-format sarif # SARIF格式

Inspection

检查详情

ruff check . --diff # Show what would change ruff check . --show-fixes # Show available fixes ruff check . --statistics # Show rule statistics ruff rule F401 # Explain a specific rule
ruff check . --diff # 显示将要修改的内容 ruff check . --show-fixes # 显示可用修复 ruff check . --statistics # 显示规则统计 ruff rule F401 # 解释特定规则

Development

开发工具

ruff check --watch # Watch mode ruff check . --add-noqa # Add noqa comments ruff check . --extend-select RUF100 # Find unused noqa comments
undefined
ruff check --watch # 实时监控模式 ruff check . --add-noqa # 添加noqa注释 ruff check . --extend-select RUF100 # 查找未使用的noqa注释
undefined

Exit Codes

退出码

CodeMeaning
0No violations found, or all fixed
1Violations found
2Configuration error or internal error
Modify exit behavior:
bash
ruff check . --exit-zero               # Always exit 0
ruff check . --exit-non-zero-on-fix    # Exit 1 if any violations (even if fixed)
代码含义
0未发现问题,或所有问题已修复
1发现问题
2配置错误或内部错误
修改退出行为:
bash
ruff check . --exit-zero               # 始终返回0
ruff check . --exit-non-zero-on-fix    # 即使修复了问题,只要发现过问题就返回1

CI Integration

CI集成

GitHub Actions

GitHub Actions

yaml
name: Lint
on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/ruff-action@v3
        with:
          args: "check --output-format github"
yaml
name: Lint
on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/ruff-action@v3
        with:
          args: "check --output-format github"

Pre-commit

Pre-commit

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

Troubleshooting

故障排除

IssueSolution
Rule conflicts with formatterIgnore formatting rules (E501) when using ruff format
Too many violationsStart with minimal rules (E, F), expand gradually
Too many per-file ignoresReview rule selection, consider disabling noisy rules
Slow on large codebaseEnsure .venv excluded, check for recursive symlinks
noqa not workingCheck syntax:
# noqa: F401
(colon required)
问题解决方案
规则与格式化工具冲突使用ruff format时忽略格式化相关规则(如E501)
发现过多问题从基础规则(E、F)开始,逐步扩展
按文件忽略过多重新审视规则选择,考虑禁用噪音规则
大型代码库运行缓慢确保排除.venv目录,检查是否存在递归符号链接
noqa不生效检查语法:
# noqa: F401
(必须包含冒号)

Common Rule Prefixes

常见规则前缀

PrefixSourceDescription
E/WpycodestyleStyle errors/warnings
FPyflakesLogical errors
Bflake8-bugbearCommon bugs
IisortImport sorting
UPpyupgradePython version upgrades
SIMflake8-simplifyCode simplification
Npep8-namingNaming conventions
Sflake8-banditSecurity issues
C4flake8-comprehensionsComprehension style
RUFRuffRuff-specific rules
前缀来源描述
E/Wpycodestyle代码风格错误/警告
FPyflakes逻辑错误
Bflake8-bugbear常见bug
Iisort导入排序
UPpyupgradePython版本升级适配
SIMflake8-simplify代码简化
Npep8-naming命名规范
Sflake8-bandit安全问题
C4flake8-comprehensions推导式风格
RUFRuffRuff专属规则

References

参考资料