Ruff 完全入门

Ruff 完全入门 · Ruff Complete Guide

Ruff 完全入门

面向零基础:什么是 Ruff、为什么需要它、如何安装使用、配置与实战

一、什么是 Ruff

Ruff 是一个用 Rust 编写的 Python 代码检查器(Linter)和格式化工具(Formatter),由 Astral 公司(同时也开发了 uv 等工具)开发。它能够在毫秒级别完成对整个项目的代码检查和格式化。

一句话总结:Ruff = 一个工具替代 Flake8 + Black + isort + pydocstyle + ... 的 Python 代码质量管家。

Ruff 的核心能力

Linter 检查代码风格和潜在错误(800+ 条内置规则)

Formatter 自动统一代码格式(与 Black 兼容的格式化风格)

自动修复 很多规则错误可以一键自动修复

极速 比传统工具快 10~100 倍

二、为什么需要 Ruff

2.1 Python 代码质量工具的传统困境

在 Ruff 出现之前,Python 开发者通常需要安装和使用多个独立工具来管理代码质量:

工具作用配置复杂度
Flake8代码风格检查(PEP 8)需配置多个插件
Black代码格式化需单独安装
isortimport 语句排序需单独配置
pydocstyle文档字符串规范需单独配置
pyupgrade代码升级建议需单独安装
bandit安全检查需单独安装

传统工具链的三大痛点

配置繁琐:每个工具都需要单独安装和配置,经常还要处理它们之间的兼容问题。

速度缓慢:大型项目运行一轮检查可能需要几十秒甚至几分钟,严重影响开发体验。

依赖混乱:多个工具带来了大量的依赖包,环境维护成本越来越高。

2.2 Ruff 的优势

All-in-One 一站式替代

Ruff 将 Linter(代码检查)和 Formatter(代码格式化)集成到一个工具中,内置 800+ 条规则,替代了 Flake8、Black、isort、pydocstyle 等几乎所有传统工具。

极速 性能提升 10~100 倍

Ruff 使用 Rust 语言编写,利用并行处理技术。在大型项目中,原本需要 30 秒的检查,Ruff 可能只需要 0.3 秒。

与 Black 兼容 格式统一

Ruff 的格式化器输出与 Black 完全一致,可以无缝替换 Black,无需担心格式化风格改变。

三、两个核心概念:Linter 与 Formatter

Linter 代码检查器

Linter 就像代码的“体检医生”——它分析代码,找出:

  • 未使用的变量/导入
  • 语法错误
  • 不符合 PEP 8 规范的写法
  • 潜在 Bug(如变量赋值后未使用)
  • 安全问题

Linter 只检查,不修改代码(除非使用自动修复)。

Formatter 格式化工具

Formatter 就像代码的“美容师”——它自动调整:

  • 缩进(空格/Tab)
  • 行长度
  • 空白间距
  • 引号风格
  • import 排序

Formatter 直接修改代码,统一格式。

❌ 未经 Format 的代码

import os,sys

def  hello(name):
  if name=="world":
    print("Hello,world!")
  else:
    print("Hello,"+name+"!")

✅ Ruff Format 后的代码

import os
import sys


def hello(name):
    if name == "world":
        print("Hello, world!")
    else:
        print("Hello, " + name + "!")

四、安装 Ruff

pip 安装(推荐)

pip install ruff
推荐在虚拟环境中安装

uv 安装(最快)

uv add –dev ruff
如果使用 uv 管理依赖

验证安装

ruff –version
输出版本号即安装成功

pyproject.toml 依赖

[project.optional-dependencies] dev = [“ruff”]
作为开发依赖写入项目配置

五、代码检查(Lint)

5.1 基本检查

# 检查当前目录下所有 Python 文件
ruff check .

# 检查单个文件
ruff check main.py

# 检查并尝试自动修复
ruff check . --fix

# 查看详细输出(显示问题所在行)
ruff check . --output-format=concise

5.2 规则前缀速查

前缀含义示例
EPEP 8 错误(Error)E501 行过长
WPEP 8 警告(Warning)W291 行尾空白
FPyflakes(逻辑错误)F401 未使用导入
Iisort(import 排序)I001 import 未排序
N命名规范N802 函数名应小写
UPpyupgrade(升级建议)UP009 使用新语法
Sbandit(安全检查)S101 不应使用 assert
BBugbear(常见 Bug)B008 默认参数中的可变对象
常用命令:ruff check . --select E,W,F,I 表示只检查 E(PEP8 错误)、W(PEP8 警告)、F(逻辑错误)、I(import 排序)这四类规则。

六、代码格式化(Format)

# 格式化当前目录下所有 Python 文件
ruff format .

# 格式化单个文件
ruff format main.py

# 预览格式化效果(不实际修改)
ruff format . --diff

# 检查代码是否已格式化(CI 场景常用)
ruff format . --check
注意:ruff format . 会直接修改文件。如果不确定效果,先用 ruff format . --diff 预览改动。

格式化与 Linter 的区别

对比项ruff checkruff format
作用检查代码质量和规范调整代码外观格式
是否修改文件默认不修改(–fix 可修复部分)直接修改文件
关注点逻辑错误、未使用变量、安全问题缩进、空格、换行、引号
规则数量800+ 条可选规则统一的格式化风格(类似 Black)

七、配置 Ruff

Ruff 的配置写在项目根目录的 pyproject.toml 文件中(Python 项目的标准配置文件)。

7.1 常用配置示例

[tool.ruff]
# 目标 Python 版本(影响升级建议等规则)
target-version = "py311"

# 行长度限制(默认 88,Black 兼容)
line-length = 88

# 启用的规则集合
select = [
    "E",   # PEP 8 错误
    "W",   # PEP 8 警告
    "F",   # Pyflakes 逻辑错误
    "I",   # isort import 排序
    "N",   # 命名规范
    "UP",  # pyupgrade 升级建议
    "B",   # Bugbear
    "SIM", # 简化代码
]

# 忽略某些规则
ignore = [
    "E501",  # 行过长(某些情况下太严格)
]

# 排除不需要检查的文件/目录
exclude = [
    ".git",
    "__pycache__",
    "build",
    "dist",
    "*.egg-info",
    "migrations",  # Django 迁移文件
]

[tool.ruff.format]
# 使用单引号还是双引号(默认双引号,Black 兼容)
quote-style = "double"
# 缩进使用 Tab 还是空格
indent-style = "space"
# 是否保留尾随逗号
skip-magic-trailing-comma = false

7.2 配置优先级

命令行参数 > pyproject.toml > 默认配置

命令行参数优先级最高,会覆盖配置文件中的设置

八、与 VS Code 集成

最推荐的开发方式:安装 VS Code 的 Ruff 扩展,实现保存时自动检查和格式化

  1. 安装 Ruff 扩展 打开 VS Code → 扩展商店 → 搜索 “Ruff” → 安装 Ruff(由 Astral 官方提供)
  2. 配置保存时自动格式化 “editor.formatOnSave”: true, “[python]”: { “editor.defaultFormatter”: “charliermarsh.ruff”, “editor.codeActionsOnSave”: { “source.fixAll.ruff”: “explicit”, “source.organizeImports.ruff”: “explicit” } } 将以上配置添加到 VS Code 的 settings.json 中。保存 Python 文件时,Ruff 会自动格式化代码并修复可自动修复的问题。
  3. 体验自动修复 打开一个有问题的 Python 文件(如未使用的导入),保存后 Ruff 会自动移除多余的导入并格式化代码。
配置说明:source.fixAll.ruff 表示保存时自动修复可修复的 lint 错误;source.organizeImports.ruff 表示保存时自动整理 import 语句排序。

九、日常开发工作流

写代码 Ctrl+S 保存 Ruff 自动 Format + Fix 继续开发

提交前的检查流程

  1. 格式化所有代码 ruff format .
  2. 检查并修复问题 ruff check . –fix
  3. 查看剩余无法自动修复的问题 ruff check . 手动修复剩余问题后,即可提交代码
推荐脚本:可以在 package.jsonMakefile 中添加快捷命令:
ruff check . --fix && ruff format . — 一键检查并格式化整个项目。

十、常用命令速查表

场景命令
检查项目ruff check .
检查并自动修复ruff check . --fix
格式化项目ruff format .
预览格式化差异ruff format . --diff
检查是否已格式化(CI)ruff format . --check
检查单个文件ruff check main.py
查看帮助ruff --help
查看版本ruff --version
总结:Ruff 是目前 Python 生态中最推荐的代码质量工具。它用一个工具替代了 Flake8 + Black + isort + pydocstyle 等整套工具链,速度快、配置简单、与 VS Code 无缝集成。日常只需记住两条命令:ruff check . --fixruff format .

Ruff Complete Guide

For beginners: what Ruff is, why you need it, how to install, configure, and use it

1. What is Ruff

Ruff is a Python linter and formatter written in Rust, developed by Astral (the same company behind uv). It can lint and format entire projects in milliseconds.

In a nutshell: Ruff = one tool that replaces Flake8 + Black + isort + pydocstyle + ... for Python code quality.

Core Capabilities

Linter Check code style and catch errors (800+ built-in rules)

Formatter Auto-format code (Black-compatible style)

Auto-fix Many issues can be fixed with one command

Lightning fast 10-100x faster than traditional tools

2. Why Ruff

2.1 The Traditional Python Toolchain Problem

Before Ruff, Python developers needed multiple separate tools for code quality:

ToolPurposeConfig
Flake8Style checking (PEP 8)Multiple plugins needed
BlackCode formattingSeparate install
isortImport sortingSeparate config
pydocstyleDocstring conventionsSeparate config
pyupgradeUpgrade suggestionsSeparate install
banditSecurity checksSeparate install

Three Pain Points of Traditional Tools

Tedious configuration: Each tool needs separate setup, and compatibility between them is often problematic.

Slow execution: Running checks on large projects can take 30+ seconds — painful for daily development.

Dependency bloat: Many tools bring in lots of dependencies, increasing environment maintenance cost.

2.2 Ruff’s Advantages

All-in-One One Tool to Rule Them All

Ruff integrates linter and formatter into a single tool with 800+ built-in rules, replacing Flake8, Black, isort, pydocstyle, and more.

Blazing Fast 10-100x Performance

Written in Rust with parallel processing. A 30-second check on a large project might finish in 0.3 seconds with Ruff.

Black-Compatible Consistent Formatting

Ruff’s formatter produces identical output to Black, allowing seamless replacement without style changes.

3. Linter vs Formatter

Linter Code Analyzer

A Linter is like a “code doctor” — it analyzes code and finds:

  • Unused variables/imports
  • Syntax errors
  • PEP 8 violations
  • Potential bugs
  • Security issues

A Linter reads only, it doesn’t modify code (unless auto-fix is used).

Formatter Code Beautifier

A Formatter is like a “code stylist” — it automatically adjusts:

  • Indentation
  • Line length
  • Whitespace
  • Quote style
  • Import sorting

A Formatter directly modifies code to enforce consistent style.

❌ Before Format

import os,sys

def  hello(name):
  if name=="world":
    print("Hello,world!")
  else:
    print("Hello,"+name+"!")

✅ After Ruff Format

import os
import sys


def hello(name):
    if name == "world":
        print("Hello, world!")
    else:
        print("Hello, " + name + "!")

4. Installation

pip (Recommended)

pip install ruff
Best installed in a virtual environment

uv (Fastest)

uv add –dev ruff
If using uv for dependency management

Verify Install

ruff –version
Shows version number if installed correctly

pyproject.toml

[project.optional-dependencies] dev = [“ruff”]
Add as a dev dependency in project config

5. Code Checking (Lint)

5.1 Basic Checking

# Check all Python files in current directory
ruff check .

# Check a single file
ruff check main.py

# Check and attempt auto-fix
ruff check . --fix

# Detailed output (show affected lines)
ruff check . --output-format=concise

5.2 Rule Prefix Reference

PrefixCategoryExample
EPEP 8 ErrorsE501 line too long
WPEP 8 WarningsW291 trailing whitespace
FPyflakes (logic)F401 unused import
Iisort (imports)I001 unsorted imports
NNaming conventionsN802 function naming
UPpyupgradeUP009 use modern syntax
Sbandit (security)S101 no assert in production
BBugbearB008 mutable default arg
Common usage:ruff check . --select E,W,F,I checks only E (PEP8 errors), W (warnings), F (logic), and I (import sorting) rules.

6. Code Formatting (Format)

# Format all Python files in current directory
ruff format .

# Format a single file
ruff format main.py

# Preview changes without modifying files
ruff format . --diff

# Check if code is formatted (useful in CI)
ruff format . --check
Warning:ruff format . directly modifies files. Use ruff format . --diff to preview first.

check vs format Comparison

Aspectruff checkruff format
PurposeCheck code quality & standardsAdjust code appearance
Modifies files?No by default (–fix for some)Yes, directly
FocusLogic errors, unused vars, securityIndentation, spaces, line breaks
Rules800+ optional rulesUnified formatting style (Black-like)

7. Configuration

Ruff configuration lives in the project’s pyproject.toml file (the standard Python project config file).

7.1 Common Configuration

[tool.ruff]
# Target Python version
target-version = "py311"

# Line length limit (default 88, Black-compatible)
line-length = 88

# Enabled rule sets
select = [
    "E",   # PEP 8 errors
    "W",   # PEP 8 warnings
    "F",   # Pyflakes
    "I",   # isort
    "N",   # naming
    "UP",  # pyupgrade
    "B",   # bugbear
    "SIM", # simplification
]

# Ignore specific rules
ignore = [
    "E501",  # line too long (sometimes too strict)
]

# Exclude files/directories
exclude = [
    ".git",
    "__pycache__",
    "build",
    "dist",
    "*.egg-info",
    "migrations",
]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false

7.2 Configuration Precedence

CLI args > pyproject.toml > Defaults

Command-line arguments have highest priority and override config file settings

8. VS Code Integration

Recommended workflow: install the Ruff VS Code extension for auto-format on save.

  1. Install the Ruff Extension VS Code → Extensions → Search “Ruff” → Install Ruff by Astral
  2. Configure auto-format on save “editor.formatOnSave”: true, “[python]”: { “editor.defaultFormatter”: “charliermarsh.ruff”, “editor.codeActionsOnSave”: { “source.fixAll.ruff”: “explicit”, “source.organizeImports.ruff”: “explicit” } } Add to VS Code’s settings.json. Ruff auto-formats and fixes on save.
  3. Test auto-fixing Open a Python file with issues (e.g., unused imports). Save and watch Ruff clean it up automatically.
Config note:source.fixAll.ruff auto-fixes lint errors on save; source.organizeImports.ruff sorts imports automatically.

9. Daily Workflow

Write code Ctrl+S Ruff auto Format + Fix Continue

Pre-Commit Check

  1. Format all code ruff format .
  2. Check and fix issues ruff check . –fix
  3. Review remaining issues ruff check . Manually fix any remaining issues, then commit
Tip: Add a shortcut to package.json or Makefile:
ruff check . --fix && ruff format . — one command to lint and format the entire project.

10. Command Cheat Sheet

ScenarioCommand
Check projectruff check .
Check and auto-fixruff check . --fix
Format projectruff format .
Preview format changesruff format . --diff
Check formatting (CI)ruff format . --check
Check single fileruff check main.py
Helpruff --help
Versionruff --version
Summary: Ruff is the most recommended Python code quality tool today. It replaces the entire Flake8 + Black + isort + pydocstyle toolchain with a single fast tool that integrates seamlessly with VS Code. Just remember two commands: ruff check . --fix and ruff format ..