Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b1d17ef

Browse files
authored
Fix comment handling when parenthesising conditional expressions (psf#4134)
Fixes psf#3555
1 parent 4ceed0b commit b1d17ef

3 files changed

Lines changed: 47 additions & 0 deletions

File tree

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

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

17+
- Fix comment handling when parenthesising conditional expressions (#4134)
1718
- Format module docstrings the same as class and function docstrings (#4095)
1819
- Fix bug where spaces were not added around parenthesized walruses in subscripts,
1920
unlike other binary operators (#4109)

src/black/linegen.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,12 @@ def visit_test(self, node: Node) -> Iterator[Line]:
170170
)
171171

172172
if not already_parenthesized:
173+
# Similar to logic in wrap_in_parentheses
173174
lpar = Leaf(token.LPAR, "")
174175
rpar = Leaf(token.RPAR, "")
176+
prefix = node.prefix
177+
node.prefix = ""
178+
lpar.prefix = prefix
175179
node.insert_child(0, lpar)
176180
node.append_child(rpar)
177181

tests/data/cases/conditional_expression.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,28 @@ def something():
6767
else ValuesListIterable
6868
)
6969

70+
71+
def foo(wait: bool = True):
72+
# This comment is two
73+
# lines long
74+
75+
# This is only one
76+
time.sleep(1) if wait else None
77+
time.sleep(1) if wait else None
78+
79+
# With newline above
80+
time.sleep(1) if wait else None
81+
# Without newline above
82+
time.sleep(1) if wait else None
83+
84+
85+
a = "".join(
86+
(
87+
"", # comment
88+
"" if True else "",
89+
)
90+
)
91+
7092
# output
7193

7294
long_kwargs_single_line = my_function(
@@ -159,3 +181,23 @@ def something():
159181
if named
160182
else FlatValuesListIterable if flat else ValuesListIterable
161183
)
184+
185+
186+
def foo(wait: bool = True):
187+
# This comment is two
188+
# lines long
189+
190+
# This is only one
191+
time.sleep(1) if wait else None
192+
time.sleep(1) if wait else None
193+
194+
# With newline above
195+
time.sleep(1) if wait else None
196+
# Without newline above
197+
time.sleep(1) if wait else None
198+
199+
200+
a = "".join((
201+
"", # comment
202+
"" if True else "",
203+
))

0 commit comments

Comments
 (0)