Rust 重写 Python 死代码检测工具提速 20 倍

原标题:Show HN: Unref – A Python dead code finder built on Ruff's parser
62AI 研判分

Unref 是一款用 Rust 编写、基于 Ruff 解析器的 Python 死代码检测工具,检测整个 CPython 代码库(约 2300 个文件)耗时不到 1 秒,比 vulture 快 20 倍。它按模块匹配名称以避免跨模块误判,内置 pytest、Pydantic、SQLAlchemy 等框架规则,并沿用 Ruff 的配置与输出风格,可通过 uvx、pre-commit 或 GitHub Actions 直接接入 CI。

报道正文

unref

An extremely fast Python dead code finder, written in Rust.

Checking the whole CPython codebase (v3.15.0, about 2,300 files), measured with scripts/benchmark.py .

  • Fast: 20x faster than vulture, it checks all of CPython in under a second.
  • Just works: built-in rules for pytest, Pydantic, SQLAlchemy and more, so most projects need little or no configuration.
  • Accurate: names are matched by module, so a used parse in one module does not hide an unused parse in another.
  • Ruff-style: same conventions, options and output style as Ruff, and it finds the unused code Ruff leaves out.
  • Modern: ty-style rule codes, configuration in pyproject.toml, built on Ruff's parser.
  • Fits your workflow: runs with uvx, as a pre-commit or prek hook, and in GitHub Actions.

Documentation: unref.readthedocs.io

Getting Started

Run it with uvx:

BASH
$ uvx unref
src/project/models.py:12:7: unused-class 'Account'
src/project/utils.py:40:5: unused-function 'parse_date'

Or as a pre-commit or prek hook, alongside Ruff:

YAML
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.4
    hooks:
      - id: ruff-check
      - id: ruff-format
  - repo: https://github.com/Apakottur/unref
    rev: v0.2.0 # Or run `pre-commit autoupdate`.
    hooks:
      - id: unref

作者发帖说明(HN):

I wanted a good Python dead code finder that just works, with minimal config, until Ruff adds support for that (https://github.com/astral-sh/ruff/issues/872).

None of the newer alternatives to Vulture worked out of the box on my codebases, so I decided to build one.

The first version was in Python, then I switched to Rust for speed and to reuse Ruff's parser. It checks all of CPython in under a second.

It found lots of interesting dead code in my team's codebases, and it's the first time in years we've had a Python dead code finder in our CI.

Feedback is very welcome, especially dead code it misses.