-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Format assignment expressions (FormatExprNamedExpr
)
#5613
Comments
If the named expression needs to be parenthesized, won’t it already have been parenthesized in the parsed source? (Otherwise it would’ve been invalid syntax in the first place.) So would those “exceptions” be solved by preserving original parentheses? May be misunderstanding. |
Good point, i filed this because i tried the naive solution and failed, but you're right, the tuple way of checking if there are parentheses in range is likely better |
Implemented this differently because unlike tuples even mandatory parentheses are not part of the range |
## Summary Format named expressions (walrus operator) such a `value := f()`. Unlike tuples, named expression parentheses are not part of the range even when mandatory, so mapping optional parentheses to always gives us decent formatting without implementing all [PEP 572](https://peps.python.org/pep-0572/) rules on when we need parentheses where other expressions wouldn't. We might want to revisit this decision later and implement special cases, but for now this gives us what we need. ## Test Plan black fixtures, i added some fixtures and checked django and cpython for stability. Closes #5613
Assignment expressions are those using the "walrus operator"
:=
:In general, they are easy to format, they are a sequence of target, space,
:=
, space, value with optional parentheses.The difficulty is that there are a list of exceptional cases in PEP 572 where the parentheses are mandatory based on the surrounding node, e.g. keyword argument values need parentheses. So for implementing this we either need to use the tuple way of checking if there are parentheses in range or each node in the list in PEP 572 needs to have a special case where it checks whether the expression it is about to format is a
ExprNamedExpr
and in that cases sets the parentheses to always.The text was updated successfully, but these errors were encountered: