Skip to content

Trailing comma in case pattern causes if guard to explode #4653

@dosisod

Description

@dosisod

Black is exploding the if guard in case patterns which have trailing commas in them, even if the guard expression fits in one line. The trailing comma logic should apply only to the case pattern, not the if guard.

Black d0ff3b

Playground link

Options

--line-length=88
--safe

Input

def f(x):
    match x:
        # good refactor
        case [
            y
        ] if y == 123:
            pass

        case [
            y
        ] if True:
            pass

        case [
            y,
        ] if True:
            pass

        # bad refactor
        case [
            y,
        ] if y == 123:
            pass

Output

def f(x):
    match x:
        # good refactor
        case [y] if y == 123:
            pass

        case [y] if True:
            pass

        case [
            y,
        ] if True:
            pass

        # bad refactor
        case [
            y,
        ] if (
            y == 123
        ):
            pass

Expected

This case:

    match x:
        case [
            y,
        ] if y == 123:
            pass

Should not be refactored, as the if guard can fit on one line. The pattern above is forcing a refactor as it has a trailing comma, which should not happen as the pattern and the guard are separate expressions. Using --skip-magic-trailing-comma "fixes" this, but also causes trailing commas to be ignored globally, which is not desirable.

I didn't catch this when I wrote #4214 because this issue only crops up when the pattern has trailing commas, and the if guard is a more complex expression.

Since I wrote #4214 I can fix this one as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions