HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

08-FastAPI 项目为什么要尽早上异步测试和 Ruff

第 25 / 26 段:Ruff:把静态问题消灭在写代码时

FastAPI 工程化实践 · 发布 2026-03-28 · 更新 2026-11-11 · 标签:FastAPI、Testing、Ruff、DX

Ruff:把静态问题消灭在写代码时(续)

# F401:未使用的导入 → 自动删除
import os  # 没有用到

# B006:可变默认参数 → 提醒修复
def get_items(ids: list = []):  # 危险

# UP006:旧类型注解写法 → 自动升级
from typing import List, Dict
def func(items: List[Dict]):  # 应该用 list[dict]

# SIM108:可以简化的三元表达式
x = True if condition else False  # 可以简化成 x = condition

接到本地和 CI

本地保存时自动修复:

// .vscode/settings.json
{
    "[python]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "charliermarsh.ruff"
    }
}

pre-commit 配置:

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

CI 里只检查不修复:

# .github/workflows/ci.yml
- name: Lint
  run: ruff check . && ruff format --check .