Skip to content

Formatter: Parenthesize long expressions in dicts #8437

@zanieb

Description

@zanieb

See #8436 for background.

Stable formatting of dicts with a long value results in a wrap that reduces readability

Unformatted:

if True:
    ___ = {
        "x": "---",
        "y": "--------------------------------------------------------------" if True else None,
        "z": "---",
    }

Formatted (Ruff, Black stable):

if True:
    ___ = {
        "x": "---",
        "y": "--------------------------------------------------------------"
        if True
        else None,
        "z": "---",
    }

Formatted (Black preview):

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

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

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

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

Black's preview style will remove these parenthesis:

if True:
    ___ = {
        "x": "---",
        "y": "----------------------------------------------------" if True else None,
        "z": "---",
    }

See psf/black#620 psf/black#3440

Note that Black does not remove these parenthesis for calls or lists, see #8436 and #8438

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