black
black copied to clipboard
Black unexpectedly alters comments and one-liner expressions when comments are placed above, when using --preview
Describe the bug
When a comment is placed above a one-liner expression that uses a conditional statement, and --preview
mode is on, black changes the comment and one-liner into a parenthesized block, or moves the comment to the end of the expression. The former situation with parentheses happens when the expression is preceded by at least one newline. The latter happens if there is no newline above the comment/expression. Neither of those formatting changes is expected.
This one-liner expression syntax isn't the cleanest, and I would guess black has this behavior for cases where you assign the expression result to a variable, but perhaps this situation should still be left unaltered by black.
To Reproduce
Check this out in the black playground here
Input code:
def foo(wait: bool = True):
# This full comment and the next one after it will get wrapped into
# the next one-liner unexpectedly
# even if this comment is separated
time.sleep(1) if wait else None
time.sleep(1) if wait else None
# With newline above
time.sleep(1) if wait else None
# Without newline above
time.sleep(1) if wait else None
Output using latest/main
version of black with the --preview
argument:
def foo(wait: bool = True):
( # This full comment and the next one after it will get wrapped into
# the next one-liner unexpectedly
# even if this comment is separated
time.sleep(1)
if wait
else None
)
time.sleep(1) if wait else None
(
# With newline above
time.sleep(1)
if wait
else None
)
time.sleep(1) if wait else None # Without newline above
Expected behavior: No change to the original code whatsoever. That was Black's behavior prior to the latest version, 23.1.0.
Environment
- Black's version: 23.1.0 or main
- OS and Python version: Python 3.10, Mac
Here's a related instance. Before:
tox_command_parts = filter(
None,
[
"tox",
"-vv", # extra-verbose
"-c %s " % tox_file if tox_file else None,
"-e",
tox_env,
],
)
After:
tox_command_parts = filter(
None,
[
"tox",
"-vv",
"-c %s " % tox_file if tox_file else None, # extra-verbose
"-e",
tox_env,
],
)
https://black.vercel.app/?version=main&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4AEsAKxdAD2IimZxl1N_WmhLJkqqGxy7GTEIPj6BUDFbymKtLrohg4RFtFIh7lTJX-YW74u8QDGqTzO2LRiIA5VrWv_FdeOfDy9N96Ys3SY_Trse64NMwb6iDrZLIsUeYohO6ecE_jfwzK9dqK4F0kYYt72a_z0sYJir2O9le62KLf02o9gnkRgn98pl6VVP7kkaKAJG31i__EgSBa2Bm4pkdCNpGDATo0u4nSZ_GhjjRQAAs4N_w4ZOTVsAAcgBrQIAAAJ0C7-xxGf7AgAAAAAEWVo=
Seems related to https://github.com/psf/black/pull/2278, cc @JEphron if you're around to take a look
Got another report of moving comments that traces back to parenthesize_conditional_expressions
in https://github.com/psf/black/issues/4042#issuecomment-1859231535
a = "".join(
(
"", # comment
"" if True else "",
)
)