black icon indicating copy to clipboard operation
black copied to clipboard

Comment is removed inside two pairs of parentheses

Open sagark4 opened this issue 2 years ago • 6 comments

Black https://github.com/psf/black/commit/c3235e

Playground link

Options

--line-length=88 --safe

Input

if ((
    True
    # sdf
)):
    print("hw")

Output

if True:
    print("hw")

Expected

Something like:

if (
    True
    # sdf
):
    print("hw")

sagark4 avatar Jul 26 '23 13:07 sagark4

Apologies if I missed some rules/etiquettes when posting this issue. I actually faced this issue in real-life when I took the suggestion of this SO answer to combat E129 visually indented line with same indent as next logical line (before using black). I had added a big comment inside describing the logic of the if condition, which got removed by black. Please let me know if I should add more information.

sagark4 avatar Aug 04 '23 09:08 sagark4

Wouldn't it be better to do something like this?

if True: # sdf
    print("hw")

tusharhero avatar Aug 06 '23 12:08 tusharhero

We should definitely not remove the comment. I would welcome a proposed fix.

JelleZijlstra avatar Aug 06 '23 14:08 JelleZijlstra

Well, if you blacken the following code, it stays unchanged. playground link

if (
    True
    # sdf
):
    print("hw")

sagark4 avatar Aug 06 '23 14:08 sagark4

Please also consider the case of multi-line comments. I hit this bug today as well. In my case, I had something like this:

if (
    a_long_condition
    # a long comment about
    # the condition below
    and (a or b)
):
    pass

I removed a_long_condition, ending up with:

if (
    # a long comment about
    # the condition below
    (a or b)
):
    pass

This is what I expected when I ran black:

if (
    # a long comment about
    # the condition below
    a or b
):
    pass

This is what I really wanted:

# a long comment about
# the condition below
if a or b:
    pass

And this is what I got:

if a or b:
    pass

rafaelclp avatar Sep 22 '23 19:09 rafaelclp

Changed the title, since I think this is the same issue reported in #4199

def return_true():
    return (
        (
            True  # this comment gets removed accidentally
        )
    )

hauntsaninja avatar Jan 31 '24 10:01 hauntsaninja

Interesting, it looks like there's some special logic here for type: ignore comments

-if ((
+if (
     # type: ignore
     True
-)):
+):
     print("hw")

This code results in a crash when running with --safe

if ((
    True
    # type: ignore
)):
    print("hw")

cobaltt7 avatar Feb 05 '24 17:02 cobaltt7