Search code examples
pythonline-breaksformatterpathlibruff

Avoid many line breaks when formatting long lines containing binary operators with Ruff


The ruff formatter generally wraps lines with more than 88 characters (this is the default, i.e. line-length = 88).

Unfortunately, this leads to lines of pathlib paths wrapped in an unpractical fashion:

from pathlib import Path
path_save = Path().cwd().parents[1] / "some" / "folder" / "a_very_long_and_lenghtly_file_name.csv"

After applying ruff format, the second line becomes:

path_save = (
    Path().cwd().parents[1]
    / "some"
    / "folder"
    / "a_very_long_and_lenghtly_file_name.csv"
)

Desired would be only one line break:

path_save2 = (Path().cwd().parents[1] / "some" / 
"folder" / "a_very_long_and_lenghtly_file_name.csv")

Is this possible with ruff? The line-length docs don't explain at which positions line breaks are placed. I have many python files with such pathlib paths and would appreciate some sort of solution for this with few or only one line break.


Solution

  • From the Ruff documentation:

    Like Black, the Ruff formatter does not support extensive code style configuration; however, unlike Black, it does support configuring the desired quote style, indent style, line endings, and more. (See: Configuration.)

    The only way I see with Ruff is to add # fmt: skip behind the statement or surround them with # fmt: off and # fmt: on as described in this section in the Ruff docs.

    This could look like this

    path_save2 = (Path().cwd().parents[1] / "some" / 
    "folder" / "a_very_long_and_lenghtly_file_name.csv")  # fmt: skip
    

    or like this

    # fmt: off
    path_save2 = (Path().cwd().parents[1] / "some" / 
    "folder" / "a_very_long_and_lenghtly_file_name.csv")
    path_save3 = (Path().cwd().parents[1] / "some" / 
    "folder" / "a_very_long_and_lenghtly_file_name3.csv")
    # fmt: on