Python 代码格式工具 ruff 的配置文件问题

ruff 类似于 pylintautopep8。它是一个用于 Python 项目的工具,用于代码的分析以及格式化,它是 uv 项目组开发的另一个工具。

ruff 的项目地址:https://github.com/astral-sh/ruff。项目介绍是 An extremely fast Python linter and code formatter, written in Rust.,简单明确。

根据 ruff 文档 的说明,配置 ~/.ruff.toml 文件,使用命令行 ruff format main.py,即可格式化代码。

问题:

现在碰到了这样的问题,有时候 ruff format 格式化代码时,并没有使用 ~/.ruff.toml 里的自定义设置。

分析:

查询了子命令的使用方法,加一个 -v 选项后,ruff format -v main.py 可以看到使用了配置文件的路径。

出现问题时,实际看到的是:

[xxxx-xx-xx][xx:xx:xx][ruff::resolve][DEBUG] Using Ruff default settings

这个说明了,它使用的是工具默认配置,而 ~/.ruff.toml 并没有被加载进来。

原因:

经过查询文档,在 Tutorial/Configuration 这篇文档里,有这样的描述:

To determine the appropriate settings for each Python file, Ruff
looks for the first pyproject.toml, ruff.toml, or .ruff.toml file
in the file's directory or any parent directory.

To configure Ruff, we'll add the following to the configuration
file in our project's root directory:

... ...

按这个描述,对于 $HOME 以外的 Python 代码文件,如果所在目录(以及上级目录、上上级目录、…)里没有 .ruff.toml,那就只能用 ruff 的工具默认配置,而不会用到 $HOME/.ruff.toml

Read More: