Skip to content

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

@github-actions
Copy link

diff-shades results comparing this PR (59f5997) to main (c9523f4). The full diff is available in the logs under the "Generate HTML diff report" step.

╭─────────────────────── Summary ────────────────────────╮
│ 1 projects & 1 files changed / 0 changes [+0/-0]       │
│                                                        │
│ ... out of 2 841 536 lines, 13 561 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