1. ruff 简介
ruff 是一款用 rust 编写的高性能 python 代码检查器(linter)和格式化工具(formatter),由 astral 公司开发。它的目标是作为 flake8、black、isort 等多个 python 工具的统一替代品,提供 10-100 倍的性能提升。
核心特性
- ⚡ 极致性能:比现有工具快 10-100 倍
- 🐍 pip 安装:通过
pip install ruff即可安装 - 🛠️ 统一工具:同时替代 flake8、black、isort、pydocstyle、pyupgrade、autoflake 等
- 📦 内置缓存:自动跳过未更改的文件
- 🔧 自动修复:支持大量规则的自动修复
- 📏 800+ 内置规则:包含主流 flake8 插件的重新实现
- ⌨️ 编辑器集成:官方支持 vs code 等主流编辑器
- 🌎 monorepo 友好:支持分层级联配置
性能优势
ruff 的性能提升带来了显著的开发体验改善。以下是来自实际项目的反馈:
“ruff 快到有时候我故意在代码里加个 bug 来确认它真的在运行检查” —— fastapi 创始人 sebastián ramírez
“在我 25 万行的 dagster 模块上,pylint 需要 2.5 分钟,而 ruff 检查整个代码库只需 0.4 秒” —— elementl 创始人 nick schrock
2. 安装 ruff
推荐安装方式
# 使用 uv(推荐) uv tool install ruff@latest # 全局安装 uv add --dev ruff # 添加到项目开发依赖 # 使用 pip pip install ruff # 使用 pipx pipx install ruff # 使用 uvx(无需安装) uvx ruff check # 直接运行检查 uvx ruff format # 直接运行格式化
其他安装方式
# macos/linux 独立安装脚本 curl -lssf https://astral.sh/ruff/install.sh | sh # windows 独立安装脚本 powershell -c "irm https://astral.sh/ruff/install.ps1 | iex" # homebrew (macos/linux) brew install ruff # conda conda install -c conda-forge ruff # docker docker run -v .:/io --rm ghcr.io/astral-sh/ruff check
验证安装
ruff --version ruff check --help # 查看 linter 选项 ruff format --help # 查看 formatter 选项
3. ruff linter(代码检查器)
基本用法
# 检查当前目录所有 python 文件 ruff check # 检查并自动修复问题 ruff check --fix # 监听文件变化并重新检查 ruff check --watch # 检查指定路径 ruff check path/to/code/ ruff check path/to/file.py # 检查并显示所有可用修复(包括不安全修复) ruff check --fix --unsafe-fixes # 退出码为 0 即使发现 violations ruff check --exit-zero
规则配置
ruff 使用类似 flake8 的规则代码系统(如 f401、e501)。规则通过 pyproject.toml 或 ruff.toml 配置:
# pyproject.toml [tool.ruff.lint] # 启用规则 select = ["e", "f", "b", "up", "sim", "i"] # 忽略特定规则 ignore = ["e501", "f401"] # 自动修复设置 fixable = ["all"] unfixable = ["f401"]
推荐规则集
[tool.ruff.lint]
select = [
"e", # pycodestyle 错误
"f", # pyflakes
"up", # pyupgrade
"b", # flake8-bugbear
"sim", # flake8-simplify
"i", # isort
]
自动修复安全级别
ruff 将修复分为安全修复和不安全修复:
- 安全修复:保证代码语义不变,仅移除注释当删除整个语句时
- 不安全修复:可能改变运行时行为、移除注释或改变异常类型
默认仅启用安全修复。启用不安全修复:
ruff check --fix --unsafe-fixes
错误抑制
# 忽略特定规则 x = 1 # noqa: f841 # 忽略多个规则 i = 1 # noqa: e741, f841 # 忽略所有 violations y = 2 # noqa # 文件级忽略(放在文件顶部) # ruff: noqa # 文件级忽略特定规则 # ruff: noqa: f401, e501
退出码
0:未发现 violations 或所有问题已自动修复1:发现 violations2:异常终止(配置错误、cli 选项无效或内部错误)
4. ruff formatter(代码格式化工具)
基本用法
# 格式化当前目录所有 python 文件 ruff format # 格式化指定路径 ruff format path/to/code/ ruff format path/to/file.py # 检查格式但不写入(用于 ci) ruff format --check # 格式化并显示差异 ruff format --diff
设计理念
ruff formatter 是 black 的替代品,保持 99.9% 以上的兼容性。主要差异:
- 性能显著提升
- 支持更多配置选项(引号风格、缩进风格等)
- 格式化 f-string 表达式部分
配置选项
# pyproject.toml [tool.ruff] line-length = 88 # 行长度限制(默认 88) [tool.ruff.format] quote-style = "double" # 引号风格: single/double/preserve indent-style = "space" # 缩进风格: space/tab line-ending = "auto" # 行尾: auto/lf/crlf docstring-code-format = false # 是否格式化 docstring 中的代码示例 docstring-code-line-length = "dynamic" # docstring 代码行长度
格式化抑制
# fmt: off not_formatted = 3 also_not_formatted = 4 # fmt: on # 跳过单个语句 a = [1, 2, 3, 4, 5] # fmt: skip
与 linter 的规则冲突
使用 formatter 时建议禁用以下 linter 规则:
[tool.ruff.lint]
ignore = [
"w191", # tab-indentation
"e111", # indentation-with-invalid-multiple
"e114", # indentation-with-invalid-multiple-comment
"e117", # over-indented
"d206", # docstring-tab-indentation
"d300", # triple-single-quotes
"q000", # bad-quotes-inline-string
"q001", # bad-quotes-multiline-string
"q002", # bad-quotes-docstring
"q003", # avoidable-escaped-quote
"com812", # missing-trailing-comma
"com819", # prohibited-trailing-comma
]
5. 完整配置示例
# pyproject.toml [tool.ruff] # 全局设置 line-length = 88 target-version = "py38" include = ["*.py", "*.pyi", "**/pyproject.toml"] exclude = [".git", "__pycache__", "build", "dist"] [tool.ruff.lint] # 启用规则 select = ["e", "f", "b", "up", "sim", "i"] # 忽略特定规则 ignore = ["e501", "f401"] # 自动修复设置 fixable = ["all"] unfixable = [] # 按文件忽略规则 [tool.ruff.lint.per-file-ignores] "__init__.py" = ["f401"] # 允许未使用的导入 "tests/**/*.py" = ["b"] # 测试文件不检查 bugbear [tool.ruff.format] # 格式化设置 quote-style = "double" indent-style = "space" line-ending = "auto" docstring-code-format = true # isort 设置 [tool.ruff.lint.isort] known-first-party = ["my_package"] section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]
6. 最佳实践
在项目中使用
# 1. 检查并修复代码 ruff check --fix # 2. 格式化代码 ruff format # 3. 仅排序导入 ruff check --select i --fix # 4. 检查未使用的 noqa 指令 ruff check --extend-select ruf100 --fix
git 预提交钩子
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.0
hooks:
# linter
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
# formatter
- id: ruff-format
ci/cd 集成
# github actions
- name: run ruff
run: |
pip install ruff
ruff check --exit-non-zero-on-fix
ruff format --check
编辑器集成
vs code:安装官方插件 ruff,自动启用检查和格式化
其他编辑器:通过 lsp 或插件支持,详见 编辑器集成文档
7. 性能对比
| 工具 | 功能 | 性能 | 备注 |
|---|---|---|---|
| flake8 | lint | 基准 | 需要大量插件 |
| black | format | 基准 | 社区标准 |
| isort | 导入排序 | 基准 | - |
| ruff | lint + format + sort | 10-100x 更快 | 单一工具替代 |
示例:在 cpython 代码库上(约 200k 行),ruff 检查耗时 <0.5 秒,而 flake8 需要数十秒。
8. 总结
ruff 通过 rust 的高性能实现,将 python 代码检查、格式化和导入排序统一到一个工具中,带来数量级的性能提升。它与现有工具(flake8、black、isort)高度兼容,迁移成本低,是现代 python 项目的理想选择。
快速开始命令:
pip install ruff ruff check --fix ruff format
更多详细信息请访问 ruff 官方文档。
vscode 中配置和使用 ruff 的完整指南
1. 安装 ruff vscode 扩展
方式一:图形界面安装
- 打开 vscode
- 点击左侧活动栏的扩展图标(或按
ctrl+shift+x) - 在搜索框中输入 “ruff”
- 找到 ruff 扩展(作者:charliermarsh,官方扩展)
- 点击"安装"按钮
方式二:命令行安装
code --install-extension charliermarsh.ruff
前提条件
- vscode 版本 ≥ 1.74.0(推荐 ≥ 1.80.0)
- python 3.7+ (推荐 3.10+)
- 系统已安装 ruff(扩展会自动检测或使用内置版本)
2. 基础配置(推荐设置)
在 vscode 设置中(文件 > 首选项 > 设置 或按 ctrl+,),搜索 “ruff”,添加以下配置:
核心配置(在settings.json中)
{
"[python]": {
"editor.formatonsave": true,
"editor.codeactionsonsave": {
"source.fixall.ruff": "explicit",
"source.organizeimports.ruff": "explicit"
},
"editor.defaultformatter": "charliermarsh.ruff"
}
}
配置说明:
- editor.formatonsave :保存时自动格式化代码
- source.fixall.ruff :保存时自动修复可修复的 lint 错误
- source.organizeimports.ruff :保存时自动排序导入语句
- editor.defaultformatter :将 ruff 设为 python 文件的默认格式化工具
3. 高级配置选项
3.1 全局设置(在settings.json中)
{
// 启用/禁用 ruff 扩展
"ruff.enable": true,
// 指定 python 解释器路径(如果扩展无法自动检测)
"ruff.interpreter": ["/usr/bin/python3"],
// 指定 ruff 可执行文件路径
"ruff.path": ["/home/user/.local/bin/ruff"],
// 行长度限制
"ruff.linelength": 88,
// 启用的规则集
"ruff.lint.select": ["e", "f", "w", "i"],
// 忽略的规则
"ruff.lint.ignore": ["e501"],
// 排除的文件/目录
"ruff.exclude": ["**/tests/**", "**/vendor/**"],
// 启用预览特性
"ruff.lint.preview": true,
"ruff.format.preview": true,
// 配置优先级
"ruff.configurationpreference": "filesystemfirst"
}
3.2 项目级配置(推荐)
在项目根目录创建 pyproject.toml 或 ruff.toml:
# pyproject.toml [tool.ruff] line-length = 88 target-version = "py38" include = ["*.py", "*.pyi", "**/pyproject.toml"] exclude = [".git", "__pycache__", "build", "dist"] [tool.ruff.lint] # 启用规则 select = ["e", "f", "b", "up", "sim", "i"] # 忽略规则 ignore = ["e501"] # 自动修复设置 fixable = ["all"] unfixable = [] [tool.ruff.lint.per-file-ignores] "__init__.py" = ["f401"] "tests/**/*.py" = ["b"] [tool.ruff.format] quote-style = "double" indent-style = "space" docstring-code-format = true
3.3 工作区特定配置
创建 .vscode/settings.json(仅对当前工作区生效):
{
"ruff.configuration": "${workspacefolder}/pyproject.toml",
"ruff.loglevel": "info",
"ruff.trace.server": "messages",
"python.defaultinterpreterpath": "${workspacefolder}/venv/bin/python"
}
4. 使用技巧
4.1 手动触发功能
- 格式化文档:右键 → “format document” 或按
shift+alt+f - 快速修复:在错误上按
ctrl+.选择修复方案 - 排序导入:命令面板 (
ctrl+shift+p) → “ruff: organize imports” - 运行 ruff 检查:命令面板 → “ruff: run linting”
4.2 命令面板常用命令
按 ctrl+shift+p 打开命令面板,输入:
ruff: show logs- 显示 ruff 日志ruff: restart server- 重启语言服务器ruff: run linting- 运行代码检查ruff: format document- 格式化当前文档ruff: organize imports- 排序导入语句
4.3 与 black 的迁移
如果之前使用 black,确保禁用 black 并切换到 ruff:
{
"python.formatting.provider": "none",
"[python]": {
"editor.defaultformatter": "charliermarsh.ruff"
}
}
5. 常见问题解决
5.1 扩展安装后无反应
问题:安装后没有代码检查或格式化功能
解决方案:
- 检查 ruff 版本:
ruff --version(建议 ≥ 0.5.3) - 确保 python 扩展已安装
- 检查 python 解释器选择是否正确(按
ctrl+shift+p→ “python: select interpreter”) - 查看输出面板:终端 → 输出 → 选择 “ruff” 查看日志
5.2 与 pyright 类型检查冲突
问题:ruff 和 pyright 同时运行导致重复提示
解决方案:
{
"python.analysis.diagnosticseverityoverrides": {
"reportmissingimports": "none",
"reportunusedvariable": "none"
}
}
5.3 格式化与 black 不一致
问题:团队同时使用 black 和 ruff 导致格式冲突
解决方案:
- 在
pyproject.toml中配置 ruff 的 black 兼容模式:
[tool.ruff.format] # ruff 默认就是 black 兼容的,无需特殊配置 preview = true # 启用最新的 black 兼容特性
5.4 性能问题(大文件卡顿)
解决方案:
{
"ruff.lint.run": "ontype", // 改为 onsave 减少实时检查
"files.watcherexclude": {
"**/.ruff_cache/**": true
}
}
6. 调试和日志
启用详细日志
在 settings.json 中:
{
"ruff.loglevel": "debug",
"ruff.trace.server": "verbose",
"ruff.logfile": "${workspacefolder}/.vscode/ruff.log"
}
检查 ruff 配置
在终端运行:
# 检查当前配置 ruff check --show-settings # 检查格式化配置 ruff format --show-settings
7. 版本要求和建议
| 组件 | 最低版本 | 推荐版本 |
|---|---|---|
| vscode | 1.74.0 | 1.80.0+ |
| ruff 扩展 | 2024.32.0 | 最新版 |
| ruff cli | 0.5.3 | 0.9.8+ |
| python | 3.7 | 3.10+ |
建议定期更新:
# 更新 ruff cli pip install --upgrade ruff # 更新 vscode 扩展 # 在扩展面板点击更新按钮
8. 完整配置示例
推荐的生产环境配置
// .vscode/settings.json
{
"[python]": {
"editor.defaultformatter": "charliermarsh.ruff",
"editor.formatonsave": true,
"editor.codeactionsonsave": {
"source.fixall.ruff": "explicit",
"source.organizeimports.ruff": "explicit"
},
"editor.rulers": [88],
"editor.tabsize": 4,
"editor.insertspaces": true
},
"ruff.enable": true,
"ruff.interpreter": ["${workspacefolder}/venv/bin/python"],
"ruff.lint.select": ["e", "f", "b", "up", "sim", "i"],
"ruff.lint.ignore": ["e501", "f403"],
"ruff.format.preview": true,
"ruff.lint.preview": true,
"files.associations": {
"*.pyi": "python"
}
}
按照以上配置,ruff 将在 vscode 中提供流畅的代码检查和格式化体验,大幅提升 python 开发效率。
到此这篇关于python中ruff使用指南的文章就介绍到这了,更多相关python ruff使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论