pythonpython-blackruff

How to prevent ruff formatter from adding a newline after module-level docstring?


I'm using ruff as a replacement to black formatter but I wanna keep the diff at minimum. I'm noticing that it automatically inserts a newline between the module-level docstring and the first import statement.

For example, given this code:

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

After running:

ruff format file.py --diff

It gives me this:

@@ -1,4 +1,5 @@
 """base api extension."""
+
 import abc
 from typing import List, Optional, Type
 

If I format the file, the output is like this:

"""base api extension."""

import abc
from typing import List, Optional, Type

I wanna keep the original formatting without adding that newline. I couldn't find any settings I could use to ignore this. Is there a way to configure ruff to prevent this behaviour? Thank you!

My pyproject.toml before adding ruff:

[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"

After adding ruff:

[tool.ruff]
line-length = 120
Context:
    Python: 3.11.9
    Ruff Version: 0.5.7

Solution

  • If you update your black version you'll find the same issue. This formatting change is internally called module_docstring_newlines:

    This comment on the Ruff pull request for this change confirms that there is unfortunately no config option to prevent this behaviour.

    If you read through the linked issues and pull request discussions for Black and Ruff you'll see it mentioned in both cases that the formatting change often affects lots of files, but (ignoring this large caveat) it was otherwise considered uncontroversial.