装齐三件套

pip install black ruff pre-commit

black:自动格式化

不需要任何思考——风格就是 black 风格:

black .                       # 格式化当前目录所有 .py
black --check .               # 只检查不改
# 之前
def f( x,y ): return x+y

# black 之后
def f(x, y):
    return x + y

社区 95% 项目都用 black——不再有"花括号该不该换行"这种争论。

ruff:超快的 linter(替代 flake8 / pylint / isort)

ruff check .                  # 检查代码问题
ruff check --fix .            # 能修的自动修
ruff format .                 # 格式化(兼容 black)

Rust 写的,比 flake8 快 10–100 倍。从 2024 起逐渐替代了 flake8 / pylint / isort。

pyproject.toml 配置 ruff

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = [
    "E",      # pycodestyle 错误
    "W",      # pycodestyle 警告
    "F",      # pyflakes
    "I",      # isort(自动整理 import)
    "B",      # bugbear(常见 bug)
    "UP",     # pyupgrade(用更新语法)
    "SIM",    # simplify
]
ignore = ["E501"]   # 行太长 black 已经管了

pre-commit:提交前自动跑

.pre-commit-config.yaml:

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.6.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.10.0
    hooks:
      - id: mypy
pre-commit install        # 一次性安装 git hook

之后每次 git commit 自动跑——格式有问题直接拦下来。

编辑器集成

VS Code:

  1. 装插件:RuffPylanceMypy Type Checker
  2. .vscode/settings.json:
    {
      "editor.formatOnSave": true,
      "[python]": {
        "editor.defaultFormatter": "charliermarsh.ruff",
        "editor.codeActionsOnSave": {
          "source.fixAll.ruff": "explicit",
          "source.organizeImports.ruff": "explicit"
        }
      }
    }
    

保存就自动格式化 + 修小问题。

CI 集成(GitHub Actions 示例)

.github/workflows/lint.yml:

name: lint
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install ruff mypy
      - run: ruff check .
      - run: ruff format --check .
      - run: mypy src

PR 上去自动跑——风格不达标的不能合。

别还在用 flake8 / pylint

2026 年的标准答案:

工作 老工具 新工具
格式化 autopep8 / yapf blackruff format
风格检查 flake8 + pylint ruff
import 排序 isort ruff(内置 isort 规则)
类型检查 mypy mypypyright

ruff 一个工具就替代了 isort / flake8 / pylint 大部分。

配合 type 检查

# pyproject.toml
[tool.mypy]
strict = true
python_version = "3.12"
mypy src/

或 pyright:

pip install pyright
pyright src/

一份"开箱即用"的 pyproject.toml 模板

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "mypackage"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = []

[project.optional-dependencies]
dev = ["pytest", "ruff", "mypy", "pre-commit"]

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM"]

[tool.mypy]
strict = true

[tool.pytest.ini_options]
addopts = "-v --tb=short"
testpaths = ["tests"]

新项目复制这个就够。

下一篇是高级课程的最后一篇——综合案例。