Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix comment handling when parenthesising conditional expressions #4134

Merged
merged 3 commits into from Jan 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.md
Expand Up @@ -14,6 +14,7 @@

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

- Fix comment handling when parenthesising conditional expressions (#4134)
- Format module docstrings the same as class and function docstrings (#4095)
- Fix bug where spaces were not added around parenthesized walruses in subscripts,
unlike other binary operators (#4109)
Expand Down
4 changes: 4 additions & 0 deletions src/black/linegen.py
Expand Up @@ -170,8 +170,12 @@ def visit_test(self, node: Node) -> Iterator[Line]:
)

if not already_parenthesized:
# Similar to logic in wrap_in_parentheses
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
prefix = node.prefix
node.prefix = ""
lpar.prefix = prefix
node.insert_child(0, lpar)
node.append_child(rpar)

Expand Down
42 changes: 42 additions & 0 deletions tests/data/cases/conditional_expression.py
Expand Up @@ -67,6 +67,28 @@ def something():
else ValuesListIterable
)


def foo(wait: bool = True):
# This comment is two
# lines long

# This is only one
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


a = "".join(
(
"", # comment
"" if True else "",
)
)

# output

long_kwargs_single_line = my_function(
Expand Down Expand Up @@ -159,3 +181,23 @@ def something():
if named
else FlatValuesListIterable if flat else ValuesListIterable
)


def foo(wait: bool = True):
# This comment is two
# lines long

# This is only one
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


a = "".join((
"", # comment
"" if True else "",
))