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

Parenthesize conditional expressions #2277

Closed
wants to merge 2 commits into from
Closed
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
19 changes: 19 additions & 0 deletions black.py
Expand Up @@ -1755,6 +1755,25 @@ def visit_default(self, node: LN) -> Iterator[Line]:
self.current_line.append(node)
yield from super().visit_default(node)

def visit_test(self, node: LN) -> Iterator[Line]:
"""Visit an `x if y else z` test"""

# parenthesize conditional expressions which span multiple lines
already_parenthesized = (
node.prev_sibling and node.prev_sibling.type == token.LPAR
)
as_str = str(node)
multiline = "\n" in as_str and not (
as_str.startswith("\n") or as_str.endswith("\n")
)
if not already_parenthesized and multiline:
lpar = Leaf(token.LPAR, "(")
rpar = Leaf(token.RPAR, ")")
node.insert_child(0, lpar)
node.append_child(rpar)

yield from self.visit_default(node)

def visit_INDENT(self, node: Leaf) -> Iterator[Line]:
"""Increase indentation level, maybe yield a line."""
# In blib2to3 INDENT never holds comments.
Expand Down
19 changes: 19 additions & 0 deletions tests/data/conditional_expression_kwargs.py
@@ -0,0 +1,19 @@
aaa = my_function(
foo="test, this is a sample value",
bar=some_long_value_name_foo_bar_baz
if some_boolean_variable
else some_fallback_value_foo_bar_baz,
baz="hello, this is a another value",
)

# output

aaa = my_function(
foo="test, this is a sample value",
bar=(
some_long_value_name_foo_bar_baz
if some_boolean_variable
else some_fallback_value_foo_bar_baz
),
baz="hello, this is a another value",
)
8 changes: 8 additions & 0 deletions tests/test_black.py
Expand Up @@ -280,6 +280,14 @@ def test_function2(self) -> None:
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())

@patch("black.dump_to_file", dump_to_stderr)
def test_conditional_expression_kwargs(self) -> None:
source, expected = read_data("conditional_expression_kwargs")
actual = fs(source)
self.assertFormatEqual(expected, actual)
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())

@patch("black.dump_to_file", dump_to_stderr)
def test_function_trailing_comma(self) -> None:
source, expected = read_data("function_trailing_comma")
Expand Down