black icon indicating copy to clipboard operation
black copied to clipboard

Bug: linebreak in comparison in parens with comments in conditional is not stable

Open Zac-HD opened this issue 7 years ago • 6 comments

Hypothesis is planning to adopt Black (HypothesisWorks/hypothesis#1686), but I noticed a weird linebreak when a condition follows a comment. Originally this was in this example, but the simple repro is as follows:

# Expected form
(
    # comment
    1 == 2
)
# Result of running Black on expected form
(
    # comment
    1
    == 2
)

Operating system: Windows Python version: 3.6.5 Black version: 18.9b0 Does also happen on master: yes, commit 0b40a7

(and thanks so much to everyone contributing to Black - it's made Python development noticeably more fun by taking formatting entirely out of my brain :heart_eyes:)

Zac-HD avatar Dec 12 '18 12:12 Zac-HD

Even better: applying Black to this code

if (
    # pre
    (1 == 2)
    # post
): ...

removes the inner parens, which then inserts the linebreak above. This in turn makes Black abort in --safe mode!

This more complex form only occurs if the parens are part of a more complex statement (if, while, for, etc) and does not happen in the 'expected form' above - if inner parens are added, they are retained by Black.

Zac-HD avatar Dec 16 '18 11:12 Zac-HD

Just rechecked, Black is no longer unstable, but is now deleting comments D:

ichard26 avatar Apr 02 '21 02:04 ichard26

The example from the first post is no longer unstable. In the second example, Black now removes the # pre comment, which is still a bug.

JelleZijlstra avatar May 30 '21 02:05 JelleZijlstra

Just rechecked, Black is no longer unstable, but is now deleting comments D:

I noticed this today. With

black, 23.3.0 (compiled: yes)
Python (CPython) 3.11.3

This statement will lose its # First inner comment:

# Some assert
assert (
    # First inner comment
    (1 + 1)  # Test's trailing comment 
    # Below the expression
    # Last inner comment
), "Some string"  # Message's trailing comment
# Below the assert

cnpryer avatar Jun 19 '23 19:06 cnpryer

Comments are no longer removed and Black no longer crashes on any of these examples, however the linebreak is still added.

cobaltt7 avatar Oct 26 '25 23:10 cobaltt7

It happens with many different operators, and regardless of whether the comment is before or after the expression:

(
    apple,
    banana,
    # and cucumber
)
(
    apple
    / banana
    # and cucumber
)
(
    apple
    + banana
    # and cucumber
)
(
    apple
    == banana
    # and cucumber
)
(
    apple
    or banana
    # and cucumber
)
(
    apple
    if banana
    else cucumber
    # and cucumber
)

(playground link)

wasokeli avatar Nov 14 '25 10:11 wasokeli