Skip to content

Fix bug with standalone comments in lambda default arguments #4658

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

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?

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
1 participant