如何配置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
相关产品推荐
相关产品推荐

