linting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRuff 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
undefinedbash
undefinedInstall 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
undefinedruff check --watch
undefinedCore Patterns
核心使用模式
- Start minimal: Enable and
Erules first, then gradually expandF - Auto-fix safely: Use for safe fixes only
ruff check --fix - Per-file ignores: Use sparingly for generated code or special cases
- CI integration: Use for GitHub Actions
ruff check --output-format github - Single source of truth: Configure via or
pyproject.tomlruff.toml
- 从简开始:先启用和
E规则,再逐步扩展F - 安全修复:使用仅执行安全修复
ruff check --fix - 按文件忽略:仅在生成代码或特殊场景下少量使用
- CI集成:在GitHub Actions中使用
ruff check --output-format github - 单一配置源:通过或
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., ). Rules are controlled via , , and .
F401lint.selectlint.extend-selectlint.ignoreRuff采用编码系统,每条规则由1-3个字母前缀加数字组成(例如)。可通过、和控制规则。
F401lint.selectlint.extend-selectlint.ignoreRecommended Rule Sets
推荐规则集
Minimal (Start Here):
toml
[tool.ruff.lint]
select = ["E", "F"] # pycodestyle errors + PyflakesBalanced (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 , which overrides inherited configs:
pyproject.toml- CLI (,
--select) - highest priority--ignore - Current
pyproject.toml - Inherited files
pyproject.toml
For detailed rule configuration, see references/rule_selection.md.
CLI选项优先级高于,后者又高于继承的配置:
pyproject.toml- CLI(,
--select)- 最高优先级--ignore - 当前目录的
pyproject.toml - 继承的文件
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:
| Type | Behavior | Default |
|---|---|---|
| Safe | Preserves code semantics | Enabled |
| Unsafe | May change runtime behavior | Disabled |
bash
undefinedRuff将修复分为安全和不安全两类:
| 类型 | 行为 | 默认设置 |
|---|---|---|
| 安全 | 保留代码语义 | 启用 |
| 不安全 | 可能改变代码运行行为 | 禁用 |
bash
undefinedApply 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
undefinedruff check --unsafe-fixes
undefinedAdjusting 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
undefinedpython
undefinedruff: noqa # Ignore all rules in file
ruff: noqa # 忽略当前文件所有规则
ruff: noqa: F841 # Ignore specific rule in file
ruff: noqa: F841 # 忽略当前文件的特定规则
undefinedundefinedBlock-Level (Preview Mode)
块级别(预览功能)
python
undefinedpython
undefinedruff: 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
undefinedbash
undefinedBasic 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
undefinedruff check --watch # 实时监控模式
ruff check . --add-noqa # 添加noqa注释
ruff check . --extend-select RUF100 # 查找未使用的noqa注释
undefinedExit Codes
退出码
| Code | Meaning |
|---|---|
| 0 | No violations found, or all fixed |
| 1 | Violations found |
| 2 | Configuration 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 # 即使修复了问题,只要发现过问题就返回1CI 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-formatyaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-formatTroubleshooting
故障排除
| Issue | Solution |
|---|---|
| Rule conflicts with formatter | Ignore formatting rules (E501) when using ruff format |
| Too many violations | Start with minimal rules (E, F), expand gradually |
| Too many per-file ignores | Review rule selection, consider disabling noisy rules |
| Slow on large codebase | Ensure .venv excluded, check for recursive symlinks |
| noqa not working | Check syntax: |
| 问题 | 解决方案 |
|---|---|
| 规则与格式化工具冲突 | 使用ruff format时忽略格式化相关规则(如E501) |
| 发现过多问题 | 从基础规则(E、F)开始,逐步扩展 |
| 按文件忽略过多 | 重新审视规则选择,考虑禁用噪音规则 |
| 大型代码库运行缓慢 | 确保排除.venv目录,检查是否存在递归符号链接 |
| noqa不生效 | 检查语法: |
Common Rule Prefixes
常见规则前缀
| Prefix | Source | Description |
|---|---|---|
| E/W | pycodestyle | Style errors/warnings |
| F | Pyflakes | Logical errors |
| B | flake8-bugbear | Common bugs |
| I | isort | Import sorting |
| UP | pyupgrade | Python version upgrades |
| SIM | flake8-simplify | Code simplification |
| N | pep8-naming | Naming conventions |
| S | flake8-bandit | Security issues |
| C4 | flake8-comprehensions | Comprehension style |
| RUF | Ruff | Ruff-specific rules |
| 前缀 | 来源 | 描述 |
|---|---|---|
| E/W | pycodestyle | 代码风格错误/警告 |
| F | Pyflakes | 逻辑错误 |
| B | flake8-bugbear | 常见bug |
| I | isort | 导入排序 |
| UP | pyupgrade | Python版本升级适配 |
| SIM | flake8-simplify | 代码简化 |
| N | pep8-naming | 命名规范 |
| S | flake8-bandit | 安全问题 |
| C4 | flake8-comprehensions | 推导式风格 |
| RUF | Ruff | Ruff专属规则 |
References
参考资料
- Quickstart Guide
- Rule Selection Reference
- Fix Safety Guide
- Error Suppression Patterns
- Common Pitfalls
- Official Documentation
- Full Rules Reference