diff --git a/CHANGES.md b/CHANGES.md index 4fd63ac41eb..b1a6ae3bc1c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,9 @@ +- Fixed a bug where comments where mistakenly removed along with redundant parentheses + (#4218) + ### Preview style diff --git a/src/black/linegen.py b/src/black/linegen.py index 2b7fbc492cf..cc8e41dfb20 100644 --- a/src/black/linegen.py +++ b/src/black/linegen.py @@ -1553,6 +1553,9 @@ def maybe_make_parens_invisible_in_atom( not is_type_ignore_comment_string(middle.prefix.strip()) ): first.value = "" + if first.prefix.strip(): + # Preserve comments before first paren + middle.prefix = first.prefix + middle.prefix last.value = "" maybe_make_parens_invisible_in_atom( middle, @@ -1564,6 +1567,9 @@ def maybe_make_parens_invisible_in_atom( # Strip the invisible parens from `middle` by replacing # it with the child in-between the invisible parens middle.replace(middle.children[1]) + if middle.children[-1].prefix.strip(): + # Preserve comments before last paren + last.prefix = middle.children[-1].prefix + last.prefix return False diff --git a/tests/data/cases/comments_in_double_parens.py b/tests/data/cases/comments_in_double_parens.py new file mode 100644 index 00000000000..80e7a5e5bf5 --- /dev/null +++ b/tests/data/cases/comments_in_double_parens.py @@ -0,0 +1,113 @@ +if ( + True + # sdf +): + print("hw") + +if (( + True + # sdf +)): + print("hw") + +if (( + # type: ignore + True +)): + print("hw") + +if (( + True + # type: ignore +)): + print("hw") + +if ( + # a long comment about + # the condition below + (a or b) +): + pass + +def return_true(): + return ( + ( + True # this comment gets removed accidentally + ) + ) + +def return_true(): + return (True) # this comment gets removed accidentally + + +if ( + # huh comment + (True) +): + ... + +if ( + # huh + ( + # comment + True + ) +): + ... + + +# output + +if ( + True + # sdf +): + print("hw") + +if ( + True + # sdf +): + print("hw") + +if ( + # type: ignore + True +): + print("hw") + +if ( + True + # type: ignore +): + print("hw") + +if ( + # a long comment about + # the condition below + a + or b +): + pass + + +def return_true(): + return True # this comment gets removed accidentally + + +def return_true(): + return True # this comment gets removed accidentally + + +if ( + # huh comment + True +): + ... + +if ( + # huh + # comment + True +): + ...