Bug: linebreak in comparison in parens with comments in conditional is not stable
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:)
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.
Just rechecked, Black is no longer unstable, but is now deleting comments D:
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.
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
Comments are no longer removed and Black no longer crashes on any of these examples, however the linebreak is still added.
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
)