ruff-linting

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ruff Linting

Ruff 代码检查

Expert knowledge for using
ruff check
as an extremely fast Python linter with comprehensive rule support and automatic fixing.
本内容为你提供使用
ruff check
作为超快速Python代码检查工具的专业知识,它支持丰富的规则且具备自动修复功能。

Core Expertise

核心优势

ruff Advantages
  • Extremely fast (10-100x faster than Flake8)
  • Written in Rust for performance
  • Replaces multiple tools (Flake8, pylint, isort, pyupgrade, etc.)
  • Auto-fix capabilities for many rules
  • Compatible with existing configurations
  • Over 800 built-in rules
Ruff 优势
  • 速度极快(比Flake8快10-100倍)
  • 基于Rust编写,性能出色
  • 可替代多款工具(Flake8、pylint、isort、pyupgrade等)
  • 支持对多数规则进行自动修复
  • 兼容现有配置
  • 内置超过800条规则

Basic Usage

基础用法

Simple Linting

简单代码检查

bash
undefined
bash
undefined

Lint current directory

检查当前目录

ruff check
ruff check

Lint specific files or directories

检查指定文件或目录

ruff check path/to/file.py ruff check src/ tests/
ruff check path/to/file.py ruff check src/ tests/

IMPORTANT: Pass directory as parameter to stay in repo root

重要提示:将目录作为参数传入,以保持在仓库根目录执行

✅ Good

✅ 正确做法

ruff check services/orchestrator
ruff check services/orchestrator

❌ Bad

❌ 错误做法

cd services/orchestrator && ruff check
undefined
cd services/orchestrator && ruff check
undefined

Auto-Fixing

自动修复

bash
undefined
bash
undefined

Show what would be fixed (diff preview)

预览将要修复的内容(差异对比)

ruff check --diff
ruff check --diff

Apply safe automatic fixes

应用安全的自动修复

ruff check --fix
ruff check --fix

Fix specific files

修复指定文件

ruff check --fix src/main.py
ruff check --fix src/main.py

Fix with preview (see changes before applying)

先预览再修复(应用前查看变更)

ruff check --diff services/orchestrator ruff check --fix services/orchestrator
undefined
ruff check --diff services/orchestrator ruff check --fix services/orchestrator
undefined

Output Formats

输出格式

bash
undefined
bash
undefined

Default output

默认输出

ruff check
ruff check

Show statistics

显示统计信息

ruff check --statistics
ruff check --statistics

JSON output for tooling

供工具调用的JSON格式输出

ruff check --output-format json
ruff check --output-format json

GitHub Actions annotations

GitHub Actions 注释格式

ruff check --output-format github
ruff check --output-format github

GitLab Code Quality report

GitLab 代码质量报告格式

ruff check --output-format gitlab
ruff check --output-format gitlab

Concise output

简洁输出格式

ruff check --output-format concise
undefined
ruff check --output-format concise
undefined

Rule Selection

规则选择

Common Rule Codes

常用规则代码

CodeDescriptionExample Rules
E
pycodestyle errorsE501 (line too long)
F
PyflakesF401 (unused import)
W
pycodestyle warningsW605 (invalid escape)
B
flake8-bugbearB006 (mutable default)
I
isortI001 (unsorted imports)
UP
pyupgradeUP006 (deprecated types)
SIM
flake8-simplifySIM102 (nested if)
D
pydocstyleD100 (missing docstring)
N
pep8-namingN806 (variable naming)
S
flake8-bandit (security)S101 (assert usage)
C4
flake8-comprehensionsC400 (unnecessary generator)
代码描述示例规则
E
pycodestyle 错误类规则E501(行过长)
F
Pyflakes 规则F401(未使用的导入)
W
pycodestyle 警告类规则W605(无效转义字符)
B
flake8-bugbear 规则B006(可变默认参数)
I
isort 规则I001(导入未排序)
UP
pyupgrade 规则UP006(已弃用类型)
SIM
flake8-simplify 规则SIM102(嵌套if语句)
D
pydocstyle 规则D100(缺少文档字符串)
N
pep8-naming 规则N806(变量命名不规范)
S
flake8-bandit(安全类)规则S101(使用assert)
C4
flake8-comprehensions 规则C400(不必要的生成器)

Selecting Rules

选择规则

bash
undefined
bash
undefined

Select specific rules at runtime

在运行时选择特定规则

ruff check --select E,F,B,I
ruff check --select E,F,B,I

Extend default selection

扩展默认规则集

ruff check --extend-select UP,SIM
ruff check --extend-select UP,SIM

Ignore specific rules

忽略特定规则

ruff check --ignore E501,E402
ruff check --ignore E501,E402

Show which rules would apply

查看将应用的规则

ruff rule --all
ruff rule --all

Explain a specific rule

查看特定规则的说明

ruff rule F401
undefined
ruff rule F401
undefined

Rule Queries

规则查询

bash
undefined
bash
undefined

List all available rules

列出所有可用规则

ruff rule --all
ruff rule --all

Search for rules by pattern

按模式搜索规则

ruff rule --all | grep "import"
ruff rule --all | grep "import"

Get detailed rule explanation

获取规则的详细说明

ruff rule F401
ruff rule F401

Output: unused-import (F401)

输出:unused-import (F401)

Derived from the Pyflakes linter.

源自Pyflakes检查器。

Checks for unused imports.

检查未使用的导入。

List all linters

列出所有检查器

ruff linter
ruff linter

JSON output for automation

供自动化使用的JSON格式输出

ruff rule F401 --output-format json
undefined
ruff rule F401 --output-format json
undefined

Configuration

配置

pyproject.toml

pyproject.toml

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

Line length limit (same as Black)

行长度限制(与Black一致)

line-length = 88
line-length = 88

Target Python version

目标Python版本

target-version = "py311"
target-version = "py311"

Exclude directories

排除目录

exclude = [ ".git", ".venv", "pycache", "build", "dist", ]
[tool.ruff.lint]
exclude = [ ".git", ".venv", "pycache", "build", "dist", ]
[tool.ruff.lint]

Enable specific rule sets

启用特定规则集

select = [ "E", # pycodestyle errors "F", # Pyflakes "B", # flake8-bugbear "I", # isort "UP", # pyupgrade "SIM", # flake8-simplify ]
select = [ "E", # pycodestyle 错误类规则 "F", # Pyflakes 规则 "B", # flake8-bugbear 规则 "I", # isort 规则 "UP", # pyupgrade 规则 "SIM", # flake8-simplify 规则 ]

Disable specific rules

禁用特定规则

ignore = [ "E501", # Line too long (handled by formatter) "B008", # Function calls in argument defaults ]
ignore = [ "E501", # 行过长(由格式化工具处理) "B008", # 参数默认值中调用函数 ]

Allow automatic fixes

允许自动修复

fixable = ["ALL"] unfixable = ["B"] # Don't auto-fix bugbear rules
fixable = ["ALL"] unfixable = ["B"] # 不对bugbear规则进行自动修复

Per-file ignores

按文件忽略规则

[tool.ruff.lint.per-file-ignores] "init.py" = ["F401", "E402"] "tests/**/*.py" = ["S101"] # Allow assert in tests
undefined
[tool.ruff.lint.per-file-ignores] "init.py" = ["F401", "E402"] "tests/**/*.py" = ["S101"] # 允许在测试中使用assert
undefined

ruff.toml (standalone)

ruff.toml(独立配置文件)

toml
undefined
toml
undefined

Same options as pyproject.toml but without [tool.ruff] prefix

配置项与pyproject.toml相同,但无需[tool.ruff]前缀

line-length = 100 target-version = "py39"
[lint] select = ["E", "F", "B"] ignore = ["E501"]
[lint.isort] known-first-party = ["myapp"] force-single-line = true
undefined
line-length = 100 target-version = "py39"
[lint] select = ["E", "F", "B"] ignore = ["E501"]
[lint.isort] known-first-party = ["myapp"] force-single-line = true
undefined

Advanced Usage

进阶用法

Per-File Configuration

按文件配置

bash
undefined
bash
undefined

Override settings for specific paths

为特定路径覆盖配置

ruff check --config path/to/ruff.toml
ruff check --config path/to/ruff.toml

Use inline configuration

使用行内配置

ruff check --select E,F,B --ignore E501
undefined
ruff check --select E,F,B --ignore E501
undefined

Targeting Specific Issues

针对特定问题检查

bash
undefined
bash
undefined

Check only specific rule codes

仅检查特定规则代码

ruff check --select F401,F841 # Only unused imports/variables
ruff check --select F401,F841 # 仅检查未使用的导入/变量

Security-focused check

安全聚焦检查

ruff check --select S # All bandit rules
ruff check --select S # 所有bandit规则

Import organization only

仅检查导入排序

ruff check --select I --fix
ruff check --select I --fix

Docstring checks

文档字符串检查

ruff check --select D
undefined
ruff check --select D
undefined

Integration Patterns

集成模式

bash
undefined
bash
undefined

Check only changed files (git)

仅检查已变更的文件(git)

git diff --name-only --diff-filter=d | grep '.py$' | xargs ruff check
git diff --name-only --diff-filter=d | grep '.py$' | xargs ruff check

Check files modified in branch

检查分支中修改的文件

git diff --name-only main...HEAD | grep '.py$' | xargs ruff check
git diff --name-only main...HEAD | grep '.py$' | xargs ruff check

Parallel checking of multiple directories

并行检查多个目录

ruff check src/ & ruff check tests/ & wait
ruff check src/ & ruff check tests/ & wait

Combine with other tools

与其他工具结合使用

ruff check && pytest && mypy
undefined
ruff check && pytest && mypy
undefined

CI/CD Integration

CI/CD集成

Pre-commit Hook

Pre-commit 钩子

yaml
undefined
yaml
undefined

.pre-commit-config.yaml

.pre-commit-config.yaml

repos:
  • Linter with auto-fix

    • id: ruff-check args: [--fix]

    Advanced configuration

    • id: ruff-check name: Ruff linter args:
      • --fix
      • --config=pyproject.toml
      • --select=E,F,B,I types_or: [python, pyi, jupyter]
undefined
repos:
  • 带自动修复的代码检查器

    • id: ruff-check args: [--fix]

    进阶配置

    • id: ruff-check name: Ruff linter args:
      • --fix
      • --config=pyproject.toml
      • --select=E,F,B,I types_or: [python, pyi, jupyter]
undefined

GitHub Actions

GitHub Actions

yaml
undefined
yaml
undefined

.github/workflows/lint.yml

.github/workflows/lint.yml

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'
      changed-files: 'true'

  # Or using pip
  - name: Install ruff
    run: pip install ruff

  - name: Run linter
    run: ruff check --output-format github
undefined
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'
      changed-files: 'true'

  # 或使用pip安装
  - name: Install ruff
    run: pip install ruff

  - name: Run linter
    run: ruff check --output-format github
undefined

GitLab CI

GitLab CI

yaml
undefined
yaml
undefined

.gitlab-ci.yml

.gitlab-ci.yml

Ruff Check: stage: build image: ghcr.io/astral-sh/ruff:0.14.0-alpine script: - ruff check --output-format=gitlab > code-quality-report.json artifacts: reports: codequality: code-quality-report.json
undefined
Ruff Check: stage: build image: ghcr.io/astral-sh/ruff:0.14.0-alpine script: - ruff check --output-format=gitlab > code-quality-report.json artifacts: reports: codequality: code-quality-report.json
undefined

Common Patterns

常见使用场景

Finding Specific Issues

查找特定问题

bash
undefined
bash
undefined

Find unused imports

查找未使用的导入

ruff check --select F401
ruff check --select F401

Find mutable default arguments

查找可变默认参数

ruff check --select B006
ruff check --select B006

Find deprecated type usage

查找已弃用的类型使用

ruff check --select UP006
ruff check --select UP006

Security issues

安全问题检查

ruff check --select S
ruff check --select S

Code complexity

代码复杂度检查

ruff check --select C901
ruff check --select C901

Find all TODOs

查找所有TODO注释

ruff check --select FIX # flake8-fixme
undefined
ruff check --select FIX # flake8-fixme规则
undefined

Gradual Adoption

逐步引入

bash
undefined
bash
undefined

Start with minimal rules

从最小规则集开始

ruff check --select E,F
ruff check --select E,F

Add bugbear

添加bugbear规则

ruff check --select E,F,B
ruff check --select E,F,B

Add import sorting

添加导入排序规则

ruff check --select E,F,B,I --fix
ruff check --select E,F,B,I --fix

Add pyupgrade

添加pyupgrade规则

ruff check --select E,F,B,I,UP --fix
ruff check --select E,F,B,I,UP --fix

Generate baseline configuration

生成基线配置

ruff check --select ALL --ignore <violations> > ruff-baseline.toml
undefined
ruff check --select ALL --ignore <violations> > ruff-baseline.toml
undefined

Refactoring Support

重构支持

bash
undefined
bash
undefined

Auto-fix all safe violations

自动修复所有安全的违规项

ruff check --fix
ruff check --fix

Preview changes before fixing

在修复前预览变更

ruff check --diff | less
ruff check --diff | less

Fix only imports

仅修复导入问题

ruff check --select I --fix
ruff check --select I --fix

Modernize code

代码现代化

ruff check --select UP --fix
ruff check --select UP --fix

Simplify comprehensions

简化推导式

ruff check --select C4,SIM --fix
undefined
ruff check --select C4,SIM --fix
undefined

Plugin Configuration

插件配置

isort (Import Sorting)

isort(导入排序)

toml
[tool.ruff.lint.isort]
combine-as-imports = true
known-first-party = ["myapp"]
section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]
toml
[tool.ruff.lint.isort]
combine-as-imports = true
known-first-party = ["myapp"]
section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]

flake8-quotes

flake8-quotes

toml
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "single"
multiline-quotes = "double"
toml
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "single"
multiline-quotes = "double"

pydocstyle

pydocstyle

toml
[tool.ruff.lint.pydocstyle]
convention = "google"  # or "numpy", "pep257"
toml
[tool.ruff.lint.pydocstyle]
convention = "google"  # 或 "numpy", "pep257"

pylint

pylint

toml
[tool.ruff.lint.pylint]
max-args = 10
max-branches = 15
max-returns = 8
max-statements = 60
toml
[tool.ruff.lint.pylint]
max-args = 10
max-branches = 15
max-returns = 8
max-statements = 60

Best Practices

最佳实践

When to Use ruff check
  • Code quality enforcement
  • Pre-commit validation
  • CI/CD pipelines
  • Refactoring assistance
  • Security scanning
  • Import organization
Critical: Directory Parameters
  • Always pass directory as parameter:
    ruff check services/orchestrator
  • Never use cd:
    cd services/orchestrator && ruff check
  • Reason: Parallel execution, clearer output, tool compatibility
Rule Selection Strategy
  1. Start minimal:
    select = ["E", "F"]
    (errors + pyflakes)
  2. Add bugbear:
    select = ["E", "F", "B"]
  3. Add imports:
    select = ["E", "F", "B", "I"]
  4. Add pyupgrade:
    select = ["E", "F", "B", "I", "UP"]
  5. Consider security:
    select = ["E", "F", "B", "I", "UP", "S"]
Fixable vs Unfixable
  • Mark uncertain rules as
    unfixable
    to review manually
  • Common unfixables:
    B
    (bugbear),
    F
    (pyflakes F401)
  • Let ruff fix safe rules:
    I
    (isort),
    UP
    (pyupgrade)
Common Mistakes to Avoid
  • Using
    cd
    instead of passing directory parameter
  • Enabling ALL rules immediately (use gradual adoption)
  • Not using
    --diff
    before
    --fix
  • Ignoring rule explanations (
    ruff rule <code>
    )
  • Not configuring per-file ignores for special cases
何时使用ruff check
  • 代码质量强制执行
  • 提交前验证
  • CI/CD流水线
  • 重构辅助
  • 安全扫描
  • 导入管理
关键注意事项:目录参数
  • 始终将目录作为参数传入:
    ruff check services/orchestrator
  • 切勿使用cd切换目录:
    cd services/orchestrator && ruff check
  • 原因:支持并行执行、输出更清晰、工具兼容性更好
规则选择策略
  1. 从最小规则集开始:
    select = ["E", "F"]
    (错误类规则+Pyflakes)
  2. 添加bugbear规则:
    select = ["E", "F", "B"]
  3. 添加导入排序规则:
    select = ["E", "F", "B", "I"]
  4. 添加pyupgrade规则:
    select = ["E", "F", "B", "I", "UP"]
  5. 考虑添加安全规则:
    select = ["E", "F", "B", "I", "UP", "S"]
可修复与不可修复规则
  • 将不确定的规则标记为
    unfixable
    ,手动审查
  • 常见不可修复规则:
    B
    (bugbear)、
    F
    (Pyflakes的F401)
  • 让Ruff修复安全的规则:
    I
    (isort)、
    UP
    (pyupgrade)
需避免的常见错误
  • 使用
    cd
    切换目录而非传入目录参数
  • 立即启用所有规则(应逐步引入)
  • 在使用
    --fix
    前不使用
    --diff
    预览
  • 忽略规则说明(
    ruff rule <code>
  • 不为特殊场景配置按文件忽略规则

Quick Reference

快速参考

Essential Commands

核心命令

bash
undefined
bash
undefined

Basic operations

基础操作

ruff check # Lint current directory ruff check path/to/dir # Lint specific directory ruff check --diff # Show fix preview ruff check --fix # Apply fixes
ruff check # 检查当前目录 ruff check path/to/dir # 检查指定目录 ruff check --diff # 显示修复预览 ruff check --fix # 应用修复

Rule management

规则管理

ruff rule --all # List all rules ruff rule F401 # Explain rule F401 ruff linter # List all linters
ruff rule --all # 列出所有规则 ruff rule F401 # 查看规则F401的说明 ruff linter # 列出所有检查器

Output formats

输出格式

ruff check --statistics # Show violation counts ruff check --output-format json # JSON output ruff check --output-format github # GitHub Actions format
ruff check --statistics # 显示违规统计 ruff check --output-format json # JSON格式输出 ruff check --output-format github # GitHub Actions格式输出

Selection

规则选择

ruff check --select E,F,B # Select rules ruff check --ignore E501 # Ignore rules ruff check --extend-select UP # Extend selection
undefined
ruff check --select E,F,B # 选择规则 ruff check --ignore E501 # 忽略规则 ruff check --extend-select UP # 扩展规则集
undefined

Configuration Hierarchy

配置优先级

  1. Command-line arguments (highest priority)
  2. ruff.toml
    in current directory
  3. pyproject.toml
    in current directory
  4. Parent directory configs (recursive)
  5. User config:
    ~/.config/ruff/ruff.toml
  1. 命令行参数(优先级最高)
  2. 当前目录下的
    ruff.toml
  3. 当前目录下的
    pyproject.toml
  4. 父目录配置(递归查找)
  5. 用户配置:
    ~/.config/ruff/ruff.toml

Common Rule Combinations

常用规则组合

bash
undefined
bash
undefined

Minimal safety

基础安全检查

ruff check --select E,F
ruff check --select E,F

Good default

推荐默认配置

ruff check --select E,F,B,I
ruff check --select E,F,B,I

Comprehensive

全面检查

ruff check --select E,F,B,I,UP,SIM
ruff check --select E,F,B,I,UP,SIM

Security-focused

安全聚焦检查

ruff check --select E,F,B,S
ruff check --select E,F,B,S

Docstring enforcement

文档字符串强制执行

ruff check --select D --config '[lint.pydocstyle]\nconvention = "google"'

This makes ruff check the preferred tool for fast, comprehensive Python code linting.
ruff check --select D --config '[lint.pydocstyle]\nconvention = "google"'

这使得ruff check成为快速、全面的Python代码检查首选工具。