Skip to content

Comprehension / generator, opt-in feature to preserve line breaks #11753

@Martin19037

Description

@Martin19037

Before I begin, here is some context:

I would love to incorporate ruff as a pre-commit formatter for one of our projects. We developed the habit of almost always separating comprehension target-expression, for-in statement(s), and optional if-expression(s) into separate lines, except for very short and trivial comprehensions. Naturally, this makes identifying these separate comprehension parts very easy at a glance, at the cost of a few more lines. Also, we have increased our line length somewhat.

In its current form, ruff will always collapse comprehensions to a single line if:

  • it is short enough to fit within the line length
  • there are no "magic trailing commas" in any of the comprehension parts

We do use trailing commas ourselves, so many of our hand-formatted comprehensions that contain trailing commas in any form remain more or less unchanged after running ruff format. The ones that do not, usually get collapsed to a single line mess (also due to our increased line length).

One toy-example for this would be:

[
    i + n
    for i in range(5)
    for n in range(5)
    if i < 3
]

which would be collapsed to a single line:

[i + n for i in range(5) for n in range(5) if i < 3]

which is not as easy to recognize at a glance as the original example.

Would it be possible to have an opt-in feature to always preserve line breaks in comprehensions and generators? The behavior would be the same as if there were a trailing comma anywhere in the comprehension, and each comprehension-part is given a separate line, maybe even expand the whole comprehension into separate lines if there is at least one line break in it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    formatterRelated to the formatterstyleHow should formatted code look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions