Remove parentheses around some walrus operators (#6173)

## Summary

Closes https://github.com/astral-sh/ruff/issues/5781

## Test Plan

Added cases to
`crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/named_expr.py`
one-by-one and adjusted the condition as needed.
This commit is contained in:
Charlie Marsh 2023-07-29 10:06:26 -04:00 committed by GitHub
parent 1d7ad30188
commit 5d9814d84d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 93 additions and 215 deletions

View file

@ -32,11 +32,25 @@ impl FormatNodeRule<ExprNamedExpr> for FormatExprNamedExpr {
impl NeedsParentheses for ExprNamedExpr {
fn needs_parentheses(
&self,
_parent: AnyNodeRef,
parent: AnyNodeRef,
_context: &PyFormatContext,
) -> OptionalParentheses {
// Unlike tuples, named expression parentheses are not part of the range even when
// mandatory. See [PEP 572](https://peps.python.org/pep-0572/) for details.
OptionalParentheses::Always
if parent.is_stmt_ann_assign()
|| parent.is_stmt_assign()
|| parent.is_stmt_aug_assign()
|| parent.is_stmt_assert()
|| parent.is_stmt_return()
|| parent.is_except_handler_except_handler()
|| parent.is_with_item()
|| parent.is_stmt_delete()
|| parent.is_stmt_for()
|| parent.is_stmt_async_for()
{
OptionalParentheses::Always
} else {
OptionalParentheses::Never
}
}
}