ruff-linting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseruff Linting
Ruff 代码检查
Expert knowledge for using as an extremely fast Python linter with comprehensive rule support and automatic fixing.
ruff check本内容为你提供使用作为超快速Python代码检查工具的专业知识,它支持丰富的规则且具备自动修复功能。
ruff checkCore 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
undefinedbash
undefinedLint 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
undefinedcd services/orchestrator && ruff check
undefinedAuto-Fixing
自动修复
bash
undefinedbash
undefinedShow 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
undefinedruff check --diff services/orchestrator
ruff check --fix services/orchestrator
undefinedOutput Formats
输出格式
bash
undefinedbash
undefinedDefault 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
undefinedruff check --output-format concise
undefinedRule Selection
规则选择
Common Rule Codes
常用规则代码
| Code | Description | Example Rules |
|---|---|---|
| pycodestyle errors | E501 (line too long) |
| Pyflakes | F401 (unused import) |
| pycodestyle warnings | W605 (invalid escape) |
| flake8-bugbear | B006 (mutable default) |
| isort | I001 (unsorted imports) |
| pyupgrade | UP006 (deprecated types) |
| flake8-simplify | SIM102 (nested if) |
| pydocstyle | D100 (missing docstring) |
| pep8-naming | N806 (variable naming) |
| flake8-bandit (security) | S101 (assert usage) |
| flake8-comprehensions | C400 (unnecessary generator) |
| 代码 | 描述 | 示例规则 |
|---|---|---|
| pycodestyle 错误类规则 | E501(行过长) |
| Pyflakes 规则 | F401(未使用的导入) |
| pycodestyle 警告类规则 | W605(无效转义字符) |
| flake8-bugbear 规则 | B006(可变默认参数) |
| isort 规则 | I001(导入未排序) |
| pyupgrade 规则 | UP006(已弃用类型) |
| flake8-simplify 规则 | SIM102(嵌套if语句) |
| pydocstyle 规则 | D100(缺少文档字符串) |
| pep8-naming 规则 | N806(变量命名不规范) |
| flake8-bandit(安全类)规则 | S101(使用assert) |
| flake8-comprehensions 规则 | C400(不必要的生成器) |
Selecting Rules
选择规则
bash
undefinedbash
undefinedSelect 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
undefinedruff rule F401
undefinedRule Queries
规则查询
bash
undefinedbash
undefinedList 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
undefinedruff rule F401 --output-format json
undefinedConfiguration
配置
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
undefinedruff.toml (standalone)
ruff.toml(独立配置文件)
toml
undefinedtoml
undefinedSame 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
undefinedline-length = 100
target-version = "py39"
[lint]
select = ["E", "F", "B"]
ignore = ["E501"]
[lint.isort]
known-first-party = ["myapp"]
force-single-line = true
undefinedAdvanced Usage
进阶用法
Per-File Configuration
按文件配置
bash
undefinedbash
undefinedOverride 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
undefinedruff check --select E,F,B --ignore E501
undefinedTargeting Specific Issues
针对特定问题检查
bash
undefinedbash
undefinedCheck 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
undefinedruff check --select D
undefinedIntegration Patterns
集成模式
bash
undefinedbash
undefinedCheck 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
undefinedruff check && pytest && mypy
undefinedCI/CD Integration
CI/CD集成
Pre-commit Hook
Pre-commit 钩子
yaml
undefinedyaml
undefined.pre-commit-config.yaml
.pre-commit-config.yaml
repos:
-
repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.14.0 hooks:
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]
undefinedrepos:
-
repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.14.0 hooks:
带自动修复的代码检查器
- 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]
undefinedGitHub Actions
GitHub Actions
yaml
undefinedyaml
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 githubundefinedname: 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 githubundefinedGitLab CI
GitLab CI
yaml
undefinedyaml
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
undefinedRuff 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
undefinedCommon Patterns
常见使用场景
Finding Specific Issues
查找特定问题
bash
undefinedbash
undefinedFind 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
undefinedruff check --select FIX # flake8-fixme规则
undefinedGradual Adoption
逐步引入
bash
undefinedbash
undefinedStart 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
undefinedruff check --select ALL --ignore <violations> > ruff-baseline.toml
undefinedRefactoring Support
重构支持
bash
undefinedbash
undefinedAuto-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
undefinedruff check --select C4,SIM --fix
undefinedPlugin 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 = 60toml
[tool.ruff.lint.pylint]
max-args = 10
max-branches = 15
max-returns = 8
max-statements = 60Best 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
- Start minimal: (errors + pyflakes)
select = ["E", "F"] - Add bugbear:
select = ["E", "F", "B"] - Add imports:
select = ["E", "F", "B", "I"] - Add pyupgrade:
select = ["E", "F", "B", "I", "UP"] - Consider security:
select = ["E", "F", "B", "I", "UP", "S"]
Fixable vs Unfixable
- Mark uncertain rules as to review manually
unfixable - Common unfixables: (bugbear),
B(pyflakes F401)F - Let ruff fix safe rules: (isort),
I(pyupgrade)UP
Common Mistakes to Avoid
- Using instead of passing directory parameter
cd - Enabling ALL rules immediately (use gradual adoption)
- Not using before
--diff--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 - 原因:支持并行执行、输出更清晰、工具兼容性更好
规则选择策略
- 从最小规则集开始:(错误类规则+Pyflakes)
select = ["E", "F"] - 添加bugbear规则:
select = ["E", "F", "B"] - 添加导入排序规则:
select = ["E", "F", "B", "I"] - 添加pyupgrade规则:
select = ["E", "F", "B", "I", "UP"] - 考虑添加安全规则:
select = ["E", "F", "B", "I", "UP", "S"]
可修复与不可修复规则
- 将不确定的规则标记为,手动审查
unfixable - 常见不可修复规则:(bugbear)、
B(Pyflakes的F401)F - 让Ruff修复安全的规则:(isort)、
I(pyupgrade)UP
需避免的常见错误
- 使用切换目录而非传入目录参数
cd - 立即启用所有规则(应逐步引入)
- 在使用前不使用
--fix预览--diff - 忽略规则说明()
ruff rule <code> - 不为特殊场景配置按文件忽略规则
Quick Reference
快速参考
Essential Commands
核心命令
bash
undefinedbash
undefinedBasic 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
undefinedruff check --select E,F,B # 选择规则
ruff check --ignore E501 # 忽略规则
ruff check --extend-select UP # 扩展规则集
undefinedConfiguration Hierarchy
配置优先级
- Command-line arguments (highest priority)
- in current directory
ruff.toml - in current directory
pyproject.toml - Parent directory configs (recursive)
- User config:
~/.config/ruff/ruff.toml
- 命令行参数(优先级最高)
- 当前目录下的
ruff.toml - 当前目录下的
pyproject.toml - 父目录配置(递归查找)
- 用户配置:
~/.config/ruff/ruff.toml
Common Rule Combinations
常用规则组合
bash
undefinedbash
undefinedMinimal 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代码检查首选工具。