配置 ruff 使用 numpy 规则集并自动排序 import 与格式化 dtype 字面量

解读

国内一线互联网、量化与 AI 公司普遍把“工程化”能力作为 NumPy 岗的硬杠杆:代码必须一次性通过静态检查,CI 流水线里 ruff 的耗时不能超过 100 ms,且 import 顺序、dtype 写法要符合团队规范。面试官给出这道题,表面看是“配一下 linter”,实则考察三条暗线:

  1. 是否知道 NumPy 官方在 ruff 0.1+ 之后提供了独立规则集 NPY,而不是靠 flake8-numpy 等老插件;
  2. 能否把 isort 的功能迁移到 ruff 内置的“isort”规则,并解决 NumPy 与第三方库混排时的“第一方/第三方”识别问题;
  3. 对 dtype 字面量格式化有没有“性能洁癖”——既要把 np.int64 改成 np.intp 以适配 64-bit 平台,又要避免把 np.float32 误抬成 np.float64 导致显存翻倍。答不到这三层,会被直接判定为“只写过实验脚本,没上过生产”。

知识点

  1. ruff 规则集架构:内置规则按前缀分组,NPY 为 NumPy 专属;启用方式 select = ["NPY"]。
  2. ruff 内置 isort:规则代码 I001、I002 …,可完全替代独立 isort 工具;通过 known-first-party、known-third-party 与 section-order 解决混排。
  3. NumPy dtype 字面量常见坑:
    • 平台相关类型:np.intp 等价 C ssize_t,64-bit 平台占 8 字节;np.int64 固定 8 字节,跨平台行为不同。
    • 精度标注:np.float_ 是 C double 别名,易与 np.float64 混淆;ruff NPY 规则会提示用显式 np.float64。
    • 格式化风格:团队规范通常要求 np.dtype('float32') 统一成 np.float32,且禁止字符串字面量拼 dtype。
  4. pre-commit 集成:国内公司普遍要求本地 pre-commit 与 GitLab CI 共用同一份 ruff 版本,避免“本地过、远端挂”。
  5. 性能底线:ruff 单文件 10 k 行检查耗时 < 100 ms,内存 < 50 M;若超出,需用 per-file-ignores 把大文件拆规则。

答案

  1. 安装与锁定版本

    pip install "ruff>=0.3.0,<0.4"  # 国内镜像加 -i https://pypi.tuna.tsinghua.edu.cn/simple
    pre-commit --version           # 确保 pre-commit 3.x+
    
  2. 项目根目录创建 ruff.toml(或 pyproject.toml 的 [tool.ruff] 段),核心片段如下:

    # 1. 启用 NumPy 规则集 + isort + 格式化
    select = [
        "NPY",   # NumPy 专用规则
        "I",     # isort 规则
        "UP",    # pyupgrade 保持 py38+ 语法
        "C90",   # McCabe 复杂度,可选
    ]
    ignore = [
        "NPY002",  # 若团队允许 np.float_ 可关闭
    ]
    target-version = "py38"
    
    # 2. 自动排序 import
    [tool.ruff.isort]
    section-order = ["future", "standard-library", "third-party", "first-party", "local-folder"]
    known-third-party = ["numpy", "scipy", "pandas"]
    known-first-party = ["my_project"]   # 替换为你的代码库名
    lines-between-types = 1
    force-sort-within-sections = true
    
    # 3. 格式化 dtype 字面量
    [tool.ruff.per-file-ignores]
    # 对性能敏感的文件可关闭部分规则
    "benchmark/*.py" = ["NPY001"]
    
    # 4. 统一行长度
    line-length = 88
    
  3. 验证配置

    ruff check . --select NPY --diff   # 仅看 NumPy 规则差异
    ruff check . --select I --diff     # 仅看 import 排序差异
    
  4. 自动修复并格式化 dtype

    ruff check . --fix
    ruff format .                      # ruff 0.3+ 内置 formatter,统一双引号、空格
    
  5. pre-commit 钩子 .pre-commit-config.yaml

    repos:
      - repo: https://github.com/astral-sh/ruff-pre-commit
        rev: v0.3.0
        hooks:
          - id: ruff
            args: ["--fix"]
          - id: ruff-format
    
  6. 典型修复示例
    修复前:

    import os, numpy as np
    from my_project.utils import foo
    a = np.array([1, 2, 3], dtype="int")
    b = np.int64(5)
    

    修复后:

    import os
    
    import numpy as np
    
    from my_project.utils import foo
    
    a = np.array([1, 2, 3], dtype=np.intp)
    b = np.intp(5)
    

拓展思考

  1. 多仓库 monorepo 场景下,如何给每个子包单独设置 known-first-party 而不再写死?
    思路:在子包下再放一份 ruff.toml 并设置 extend = "../ruff.toml",用 known-first-party = ["sub_a", "sub_b"] 覆盖即可;CI 阶段用 ruff check --config sub_a/ruff.toml sub_a 保证隔离。

  2. 当 NumPy 升级 2.0 后,官方把 np.int_ 等别名标记为 deprecated,ruff 规则如何同步?
    关注 ruff 的 NPY003 提案,提前在 select 里加 NPY003 并设置 preview = true,即可在正式版发布前扫出所有废弃别名,避免线上报警。

  3. dtype 字面量格式化与内存对齐的权衡:
    在深度学习数据管道里,把 np.float32 误抬成 np.float64 会让显存翻倍;但把 np.int64 降成 np.int32 又可能溢出。建议写一条自定义规则脚本,在 ruff 修复后二次扫描 *.npy 的保存代码,若出现 dtype=np.float64 且 shape 大于 1e8,自动提示 Code Review。

  4. 性能极限压测:
    对 10 万行科学计算脚本,ruff 默认线程数 4 时耗时约 80 ms;若公司 CI 机器为 2 核,可在 ruff.toml 加 cache-dir = ".cache/ruff" 并把 ruff check 改为 ruff check --cache-dir .cache/ruff --show-source,缓存命中率 > 95%,全仓库增量检查可压到 30 ms 以内,满足“秒级流水线”要求。