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

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

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