Skip to content

Commit 8af4394

Browse files
authored
fix: Don't remove comments along with parens (#4218)
Signed-off-by: RedGuy12 <[email protected]>
1 parent 35e9776 commit 8af4394

File tree

3 files changed

+122
-0
lines changed

3 files changed

+122
-0
lines changed

CHANGES.md

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010

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

13+
- Fixed a bug where comments where mistakenly removed along with redundant parentheses
14+
(#4218)
15+
1316
### Preview style
1417

1518
<!-- Changes that affect Black's preview style -->

src/black/linegen.py

+6
Original file line numberDiff line numberDiff line change
@@ -1553,6 +1553,9 @@ def maybe_make_parens_invisible_in_atom(
15531553
not is_type_ignore_comment_string(middle.prefix.strip())
15541554
):
15551555
first.value = ""
1556+
if first.prefix.strip():
1557+
# Preserve comments before first paren
1558+
middle.prefix = first.prefix + middle.prefix
15561559
last.value = ""
15571560
maybe_make_parens_invisible_in_atom(
15581561
middle,
@@ -1564,6 +1567,9 @@ def maybe_make_parens_invisible_in_atom(
15641567
# Strip the invisible parens from `middle` by replacing
15651568
# it with the child in-between the invisible parens
15661569
middle.replace(middle.children[1])
1570+
if middle.children[-1].prefix.strip():
1571+
# Preserve comments before last paren
1572+
last.prefix = middle.children[-1].prefix + last.prefix
15671573

15681574
return False
15691575

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
if (
2+
True
3+
# sdf
4+
):
5+
print("hw")
6+
7+
if ((
8+
True
9+
# sdf
10+
)):
11+
print("hw")
12+
13+
if ((
14+
# type: ignore
15+
True
16+
)):
17+
print("hw")
18+
19+
if ((
20+
True
21+
# type: ignore
22+
)):
23+
print("hw")
24+
25+
if (
26+
# a long comment about
27+
# the condition below
28+
(a or b)
29+
):
30+
pass
31+
32+
def return_true():
33+
return (
34+
(
35+
True # this comment gets removed accidentally
36+
)
37+
)
38+
39+
def return_true():
40+
return (True) # this comment gets removed accidentally
41+
42+
43+
if (
44+
# huh comment
45+
(True)
46+
):
47+
...
48+
49+
if (
50+
# huh
51+
(
52+
# comment
53+
True
54+
)
55+
):
56+
...
57+
58+
59+
# output
60+
61+
if (
62+
True
63+
# sdf
64+
):
65+
print("hw")
66+
67+
if (
68+
True
69+
# sdf
70+
):
71+
print("hw")
72+
73+
if (
74+
# type: ignore
75+
True
76+
):
77+
print("hw")
78+
79+
if (
80+
True
81+
# type: ignore
82+
):
83+
print("hw")
84+
85+
if (
86+
# a long comment about
87+
# the condition below
88+
a
89+
or b
90+
):
91+
pass
92+
93+
94+
def return_true():
95+
return True # this comment gets removed accidentally
96+
97+
98+
def return_true():
99+
return True # this comment gets removed accidentally
100+
101+
102+
if (
103+
# huh comment
104+
True
105+
):
106+
...
107+
108+
if (
109+
# huh
110+
# comment
111+
True
112+
):
113+
...

0 commit comments

Comments
 (0)