From 2cedb401bda299cd800711d26bbad3a3fc511655 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Fri, 11 Aug 2023 01:54:46 -0400 Subject: [PATCH] Force parentheses for named expressions in more contexts (#6494) See: https://github.com/astral-sh/ruff/pull/6436#issuecomment-1673583888. --- .../fixtures/ruff/expression/named_expr.py | 15 ++++++++++ .../src/expression/expr_named_expr.rs | 3 ++ .../format@expression__named_expr.py.snap | 30 +++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/named_expr.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/named_expr.py index 15ac1c7577..58522f5ad9 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/named_expr.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/named_expr.py @@ -36,3 +36,18 @@ except (e := Exception): (x := 1) (x := 1) + (y := 2) + +with (x := 1): + pass + + +def f(): + yield (x := 1) + + +def f(): + yield from (x := 1) + + +async def f(): + await (x := 1) diff --git a/crates/ruff_python_formatter/src/expression/expr_named_expr.rs b/crates/ruff_python_formatter/src/expression/expr_named_expr.rs index e0b1f674b9..935d926c30 100644 --- a/crates/ruff_python_formatter/src/expression/expr_named_expr.rs +++ b/crates/ruff_python_formatter/src/expression/expr_named_expr.rs @@ -44,6 +44,9 @@ impl NeedsParentheses for ExprNamedExpr { || parent.is_stmt_return() || parent.is_except_handler_except_handler() || parent.is_with_item() + || parent.is_expr_yield() + || parent.is_expr_yield_from() + || parent.is_expr_await() || parent.is_stmt_delete() || parent.is_stmt_for() { diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__named_expr.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__named_expr.py.snap index 018df04c72..8a57c6cb90 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__named_expr.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__named_expr.py.snap @@ -42,6 +42,21 @@ except (e := Exception): (x := 1) (x := 1) + (y := 2) + +with (x := 1): + pass + + +def f(): + yield (x := 1) + + +def f(): + yield from (x := 1) + + +async def f(): + await (x := 1) ``` ## Output @@ -82,6 +97,21 @@ except (e := Exception): (x := 1) (x := 1) + (y := 2) + +with (x := 1): + pass + + +def f(): + yield (x := 1) + + +def f(): + yield from (x := 1) + + +async def f(): + await (x := 1) ```