Skip to content

Formatter: Keep right-hanging comments alignedΒ #7684

@warsaw

Description

@warsaw

ruff format follows black's style for right-hanging comments (i.e. inline comments), but that leads to poorly readable results, especially when a series of consecutive lines uses comment alignment by column. Blue fixes this readability problem.

Let's start with this file:

def foo():
    x = 1                                         # this comment
    why = 2                                       # aligns with this comment
    zebra = 3                                     # and this one

As you can see, every # on each of these lines appears at the same column. How does ruff reformat the line?

def foo():
    x = 1  # this comment
    why = 2  # aligns with this comment
    zebra = 3  # and this one

This is the way black does it, i.e. by jamming all comment starts to two space characters between the last code character and the #. This destroys the alignment.

How does blue format the file? Nothing changes! Blue preserves the number of spaces between the last code character and the # with the assumption that the spacing is deliberate and done for readability.

ruff format should follow blue's rule here.

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