diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/unary.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/unary.py index 89ca82644a..e191045bac 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/unary.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/unary.py @@ -151,3 +151,13 @@ if ( not # comment a): ... + +# Regression test for: https://github.com/astral-sh/ruff/issues/7423 +if True: + if True: + if True: + if not yn_question( + Fore.RED + + "WARNING: Removing listed files. Do you really want to continue. yes/n)? " + ): + pass diff --git a/crates/ruff_python_formatter/src/expression/expr_unary_op.rs b/crates/ruff_python_formatter/src/expression/expr_unary_op.rs index 1b58d03571..5057a68693 100644 --- a/crates/ruff_python_formatter/src/expression/expr_unary_op.rs +++ b/crates/ruff_python_formatter/src/expression/expr_unary_op.rs @@ -82,8 +82,10 @@ impl NeedsParentheses for ExprUnaryOp { context.source(), ) { OptionalParentheses::Never + } else if context.comments().has(self.operand.as_ref()) { + OptionalParentheses::Always } else { - OptionalParentheses::Multiline + self.operand.needs_parentheses(self.into(), context) } } } diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__unary.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__unary.py.snap index 6e87a9a5e7..93114ae769 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__unary.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__unary.py.snap @@ -157,6 +157,16 @@ if ( not # comment a): ... + +# Regression test for: https://github.com/astral-sh/ruff/issues/7423 +if True: + if True: + if True: + if not yn_question( + Fore.RED + + "WARNING: Removing listed files. Do you really want to continue. yes/n)? " + ): + pass ``` ## Output @@ -323,10 +333,18 @@ if ( ): ... -if ( - not a # comment -): +if not a: # comment ... + +# Regression test for: https://github.com/astral-sh/ruff/issues/7423 +if True: + if True: + if True: + if not yn_question( + Fore.RED + + "WARNING: Removing listed files. Do you really want to continue. yes/n)? " + ): + pass ```