Skip to content

Formatting of conditional expressions in named function arguments #2248

@JEphron

Description

@JEphron

When formatting conditional expressions in function calls with named arguments, Black's formatting varies significantly depending on whether the expression is surrounded by parenthesis.

Exhibit A:

Black considers this correctly formatted

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",
)

Exhibit B

When fed the following block as input:

aaa = my_function(
    foo="hello, 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 sample value",
)

Black formats it with a much nicer indentation

aaa = my_function(
    foo="hello, 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 sample value",
)

I consider the second output far more readable. In exhibit A the if expression lies on the same indent as the kwargs, making it hard to tell what's going on. In the second, it's quite clear that some computation is spanning those three lines.

I think ideally Black would never produce Exhibit A, rather it would insert the parenthesis in order to indent the conditional expression.

In keeping with the opinionated style, we should pick one or the other, but probably not allow both. Even if Black decided to strip parenthesis and produce exhibit A all of the time, it'd be preferable to the current ambiguity.

Metadata

Metadata

Assignees

No one assigned

    Labels

    F: parenthesesToo many parentheses, not enough parentheses, and so on.T: styleWhat do we want Blackened code to look like?

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions