Skip to content

Fix bug with standalone comments in lambda default arguments#4658

Open
siavasha wants to merge 5 commits intopsf:mainfrom
siavasha:fix-lambda-comment-parsing
Open

Fix bug with standalone comments in lambda default arguments#4658
siavasha wants to merge 5 commits intopsf:mainfrom
siavasha:fix-lambda-comment-parsing

Conversation

@siavasha
Copy link

Description

Fixes #4640

This PR fixes a bug where Black would crash when formatting code with standalone comments within parentheses in lambda default arguments.

The issue occurs in the has_magic_trailing_comma method in src/black/lines.py. When a standalone comment is present within parentheses in a lambda default argument, the method tries to find the opening bracket in the line's leaves, but it wouldn't be there, causing a LookupError.

The fix adds a try-except block to catch this LookupError and return True, which causes the line to be split appropriately. This approach is consistent with how Black handles other similar cases where it needs to determine whether to add a trailing comma.

Example code that previously crashed:

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

Checklist - did you ...

  • Add an entry in CHANGES.md if necessary?
  • Add / update tests if necessary?
  • Add new / update outdated documentation?

@cobaltt7
Copy link
Collaborator

This PR introduced a crash when running on https://github.com/quora/pyanalyze/blob/master/pyanalyze%2Ftest_format_strings.py

@github-actions
Copy link

github-actions bot commented Nov 30, 2025

diff-shades results comparing this PR (fbe5d93) to main (a998a18):

--preview style (View full diff):
╭─────────────────────── Summary ────────────────────────╮
│ 1 projects & 1 files changed / 0 changes [+0/-0]       │
│                                                        │
│ ... out of 2 869 121 lines, 13 644 files & 22 projects │
╰────────────────────────────────────────────────────────╯

Differences found.

--stable style (View full diff):
╭─────────────────────── Summary ────────────────────────╮
│ 1 projects & 1 files changed / 0 changes [+0/-0]       │
│                                                        │
│ ... out of 2 869 121 lines, 13 644 files & 22 projects │
╰────────────────────────────────────────────────────────╯

Differences found.


What is this? | Workflow run | diff-shades documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Standalone comment within parentheses in lambda default arguments crashes black

2 participants