Skip to content

Standalone comment within parentheses in lambda default arguments crashes black #4640

Open
@tjstum

Description

@tjstum

Describe the bug

Given the following code snippet:

help(lambda x=(
    # comment
    "bar",
): False)

black crashes within the reformatting code with the error message:

error: cannot format <string>: Opening paren not found in `leaves`

I reproduced this using the current head of black (black, 25.1.1.dev24+g2c135ed (compiled: no)) and on the online formatter. I can see this on both Linux and macOS and multiple versions of Python (3.12 and 3.13).

I bisected the repro, and it looks like it started breaking in #4016.

Some other things I observed:

  • Using other bracket groups ([] and {}) do not show this issue
  • The magic trailing comma in the argument is important
  • If the comment comes at the end, it's fine. This does not crash:
help(lambda x=(
    "bar",
    # comment
): False)
  • Expanding on the above, comments in the middle of arguments also cause the issue:
help(lambda x=(
    "extremely lengthy argument 1 extremely lengthy argument 1",
    # comment
    "extremely lengthy argument 2 extremely lengthy argument 2",
): False)

To Reproduce

$ black --diff -v -c '''help(lambda x=(
    # comment
    "bar",
): False)
'''

Metadata

Metadata

Assignees

No one assigned

    Labels

    T: bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions