black icon indicating copy to clipboard operation
black copied to clipboard

Lambda becomes a tuple when its default has a standalone comment

Open jiteshgulati opened this issue 1 month ago • 0 comments

Describe the bug

black can turn a lambda into a tuple. if a lambda default has a comment on its own line and the lambda sits inside parentheses that have a comment after the opening paren then black adds a comma after the lambda body

To Reproduce

For example, take this code:

handler = (  # comment
    lambda x=(
        # comment
        1,
    ): x
)

And run it with these arguments:

$ black file.py

The resulting error is:

cannot format file.py: INTERNAL ERROR: Black 26.10.1 on Python (CPython) 3.12.14 produced code that is not equivalent to the source

with --fast the file gets written like this

handler = (  # comment
    lambda x=(
    # comment
    1,
    ): x,
)

so handler is now a tuple and calling it gives TypeError: 'tuple' object is not callable. running black --check on that file afterwards says it would be left unchanged so it doesn't get caught later either

Expected behavior

no comma after the lambda body so handler stays a function

Environment

  • Black's version: 26.10.1 and main
  • OS and Python version: Linux / Python 3.12.14

Additional context

the standalone comment splits the line inside the default's brackets and delimiter_split then adds a trailing comma at the end of the leftover part of the line which is outside those brackets. this shape started failing in 26.10.0 and the same code with .__name__ after the closing paren gets the extra comma since 26.3.0 (before that black crashed on it, see #4640)

the same split with --skip-magic-trailing-comma also drops the needed comma in a one element subscript like a[1,] used as a lambda default

related to #4640 and #4296. I opened #5533 with a fix

jiteshgulati avatar Oct 13 '26 23:10 jiteshgulati