Skip to content

Commit

Permalink
fix: Don't remove comments along with parens (#4218)
Browse files Browse the repository at this point in the history
Signed-off-by: RedGuy12 <61329810+RedGuy12@users.noreply.github.com>
  • Loading branch information
cobaltt7 authored Feb 12, 2024
1 parent 35e9776 commit 8af4394
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

<!-- Changes that affect Black's stable style -->

- Fixed a bug where comments where mistakenly removed along with redundant parentheses
(#4218)

### Preview style

<!-- Changes that affect Black's preview style -->
Expand Down
6 changes: 6 additions & 0 deletions src/black/linegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand Down
113 changes: 113 additions & 0 deletions tests/data/cases/comments_in_double_parens.py
Original file line number Diff line number Diff line change
@@ -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
):
...

0 comments on commit 8af4394

Please sign in to comment.