Skip to content

Odd formatting choice for long conditions with comments in list/dict comprehensions #12280

@goodspark

Description

@goodspark

Previously used search terms: format for loop if comment

Code:

x = [1, 2, 3]
y = [
    a
    for a in x 
    if (
        # asdasd
        "askldaklsdnmklasmdlkasmdlkasmdlkasmdasd" != "as,mdnaskldmlkasdmlaksdmlkasdlkasdm"
        and "zxcm,.nzxclm,zxnckmnzxckmnzxczxc" != "zxcasdasdlmnasdlknaslkdnmlaskdm"
    )
]

Comparison of Black (previous) vs Ruff (new) outputs:

 y = [
     a
     for a in x
-    if (
+    if
+    (
         # asdasd
         "askldaklsdnmklasmdlkasmdlkasmdlkasmdasd"
         != "as,mdnaskldmlkasdmlaksdmlkasdlkasdm"
Ruff's output
x = [1, 2, 3]
y = [
    a
    for a in x
    if
    (
        # asdasd
        "askldaklsdnmklasmdlkasmdlkasmdlkasmdasd"
        != "as,mdnaskldmlkasdmlaksdmlkasdlkasdm"
        and "zxcm,.nzxclm,zxnckmnzxckmnzxczxc" != "zxcasdasdlmnasdlknaslkdnmlaskdm"
    )
]
Black's output
x = [1, 2, 3]
y = [
    a
    for a in x
    if (
        # asdasd
        "askldaklsdnmklasmdlkasmdlkasmdlkasmdasd"
        != "as,mdnaskldmlkasdmlaksdmlkasdlkasdm"
        and "zxcm,.nzxclm,zxnckmnzxckmnzxczxc" != "zxcasdasdlmnasdlknaslkdnmlaskdm"
    )
]

If I move the comment out of the inner parentheses of the loop condition, the outputs match:

    for a in x 
    # asdasd
    if (

Command: ruff format

Ruff settings: None for formatting, but target-python is given at the project level, if that matters.

[project]
target-python = "==3.10"

Python version: 3.10
Ruff version: 0.5.0
Black version: 24.3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingformatterRelated to the formatter

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions