You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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(lambdax=(
"bar",
# comment
): False)
Expanding on the above, comments in the middle of arguments also cause the issue:
I've created a fix for this issue in PR #4658: #4658
In my understanding, the bug occurs because when standalone comments appear within parentheses in lambda default arguments, they create line breaks in Black's AST representation, causing the opening parenthesis to be in a different Line object than the closing parenthesis. When has_magic_trailing_comma tries to find the opening parenthesis, it can't locate it in the current line's leaves, resulting in an uncaught LookupError.
My solution adds a try-except block to catch this specific exception and handle it properly. I've included test cases that cover various scenarios including comments in different positions, multiple comments, nested lambdas with comments, and several edge cases.
I'd appreciate your review when you have a chance. Thank you!
Describe the bug
Given the following code snippet:
black crashes within the reformatting code with the error message:
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:
[]
and{}
) do not show this issueTo Reproduce
The text was updated successfully, but these errors were encountered: