Skip to content

Formatter: Parenthesize long expressions in calls #8436

@zanieb

Description

@zanieb

Stable formatting of calls with a long expression results in a wrap that reduces readability

Unformatted:

if True:
    ___ = dict(
        x="---",
        y="----------------------------------------------------------" if True else None,
        z="---",
    )

Formatted:

if True:
    ___ = dict(
        x="---",
        y="----------------------------------------------------------"
        if True
        else None,
        z="---",
    )

Adding parenthesis results in more readable code. Black's preview style does so.

if True:
    ___ = dict(
        x="---",
        y=(
            "----------------------------------------------------------"
            if True
            else None
        ),
        z="---",
    )

With a shorter line, Ruff retains parenthesis when the lines are collapsed:

if True:
    ___ = dict(
        x="---",
        y=("---------------------------------------------" if True else None),
        z="---",
    )

However, these parenthesis should be removed as they are superfluous.

Black's preview style will not remove these parenthesis for calls, but probably should.

Note Black's preview style will remove these parenthesis for dict literals, see #8437 but will not for list literals, see #8438

See also psf/black#620 psf/black#3440 psf/black#3510

Metadata

Metadata

Assignees

No one assigned

    Labels

    formatterRelated to the formatterpreviewRelated to preview mode featuresstyleHow should formatted code look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions