You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Ruff格式化器避免在模块级文档字符串后添加换行

问题

使用Ruff替代Black做代码格式化,希望最小化新旧工具的代码差异,但发现Ruff会自动在模块级文档字符串和首个导入语句之间插入空行。例如原代码:

"""base api extension."""
import abc
from typing import List, Optional, Type

执行ruff format file.py --diff后会显示添加空行的差异,格式化后文档字符串与导入间多出一行空行。需要配置Ruff保留原有格式,阻止该行为。

原有pyproject.toml配置(使用Black和isort时):

[tool.black]
line_length = 120
include = '\.py$'

[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
line_length = 120
profile = "black"

切换到Ruff后的pyproject.toml:

[tool.ruff]
line-length = 120

环境信息:Python 3.11.9,Ruff版本0.5.7

解决方案

要让Ruff在模块级文档字符串和导入语句之间不自动添加空行,需在pyproject.toml的Ruff配置中添加格式化规则,禁用blank-line-between-doc-and-imports选项:

修改后的pyproject.toml配置如下:

[tool.ruff]
line-length = 120

[tool.ruff.format]
# 禁用模块级文档字符串与导入间的强制空行
blank-line-between-doc-and-imports = false

该配置会让Ruff遵循原有代码格式,不在文档字符串与首个导入语句之间插入额外空行,与Black的行为保持一致,从而最小化代码差异。

内容的提问来源于stack exchange,提问作者Iman Shafiei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:48:14