如何基于pre-commit自动修复import排序?

解读

在 Dash 项目里,代码质量直接决定仪表盘能否稳定上线。国内大厂与金融、能源等甲方客户普遍要求“零人工干预”的 CI 流程:commit → 自动格式化 → 单测 → 镜像构建 → 部署。pre-commit 钩子就是第一道门,而 import 顺序是最容易被 Code Review 打回的高频问题。面试官问“如何自动修复”,核心想看三件事:

  1. 你是否知道 isort 与官方钩子参数;
  2. 能否把配置写进 .pre-commit-config.yaml 并保证与 Black、flake8 无冲突;
  3. 能否在本地一次性跑通,并解释给团队听,让所有人都无痛接入。

知识点

  1. isort 的五段式分组顺序(FUTURE/STDLIB/THIRDPARTY/FIRSTPARTY/LOCALFOLDER)及自定义章节。
  2. profile = "black" 的作用:行长度、引号风格、换行模式与 Black 保持一致,避免二者互改。
  3. pre-commit 钩子阶段(stages: [commit, merge-commit, push])与 pass_filenames: false 的适用场景。
  4. args: ["--filter-files"] 与 require_serial: true 对 Dash 多应用仓库的性能影响。
  5. 国内镜像加速:给 isort 加 env: PIP_INDEX_URL: https://pypi.tuna.tsinghua.edu.cn/simple。
  6. 与 Dash 生态共存的特殊规则:
    • known_dash 章节,把 dash, dash_bootstrap_components, dash_extensions 归入单独分组,方便一眼识别依赖层级。
    • 对 callbacks.py, app.py 等 Dash 约定文件强制按 __all__ 导出顺序检查,防止循环 import。

答案

步骤 1:在项目根目录创建 .pre-commit-config.yaml,写入:

repos:
  - repo: https://github.com/pycqa/isort
    rev: 5.12.0          # 国内网络建议锁定大版本
    hooks:
      - id: isort
        name: isort-fix
        stages: [commit]
        args:
          - --settings-path=pyproject.toml
          - --filter-files
        require_serial: true

步骤 2:在同目录创建 pyproject.toml,统一声明 isort 与 Black 的公共规则:

[tool.isort]
profile = "black"
line_length = 88
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
# Dash 相关库单独成组
known_dash = ["dash", "dash_bootstrap_components", "dash_extensions", "dash_mantine_components"]
sections = ["FUTURE", "STDLIB", "THIRDPARTY", "DASH", "FIRSTPARTY", "LOCALFOLDER"]

步骤 3:安装并一次性修复历史代码:

python -m pip install pre-commit isort
pre-commit install
pre-commit run isort --all-files   # 首次全量修复

步骤 4:验证与 Black 无冲突:

pre-commit run black --all-files
git diff --quiet || echo "仍有格式差异,请检查配置"

步骤 5:把 .pre-commit-config.yaml 与 pyproject.toml 加入 Git,写进 README「开发指南」:
“提交前无需手动排序 import,直接 git commit 即可,isort 会自动修复并追加到同一次 commit。”

拓展思考

  1. 大型 Dash 微前端仓库(多 app.py)如何提速?
    使用 pre-commit.ci 或 GitHub Actions 缓存 ~/.cache/pre-commit,并在 pyproject.toml 里加 skip_glob = ["*/migrations/*"] 跳过数据迁移脚本。
  2. 当团队有人用 PyCharm、有人用 VSCode,如何保持 IDE 自动保存与 pre-commit 钩子行为一致?
    在 .editorconfig 里写 max_line_length = 88,并在 IDE 的“保存操作”中调用 isort --settings-path=pyproject.toml --stdout 做实时预览,避免提交瞬间大段 diff。
  3. 如果甲方要求“零第三方外网依赖”,如何离线部署?
    提前 pre-commit download-deps 把 isort 二进制打进入口镜像,或在 GitLab CI 里用 rules:changes 只在 .pre-commit-config.yaml 变动时重新下载,其余场景走内网 PyPI 缓存。