Skip to content

Commit 3d03e75

Browse files
Force parentheses for power operations in unary expressions (#7955)
## Summary E.g., given `-10**100`, reformat as `-(10**100)`. Black special cases this (psf/black#909) and it's currently a deviation. Closes #7951.
1 parent b6e75e5 commit 3d03e75

File tree

2 files changed

+10
-12
lines changed

2 files changed

+10
-12
lines changed

crates/ruff_python_formatter/src/expression/expr_unary_op.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use ruff_python_ast::UnaryOp;
44

55
use crate::comments::{trailing_comments, SourceComment};
66
use crate::expression::parentheses::{
7-
is_expression_parenthesized, NeedsParentheses, OptionalParentheses,
7+
is_expression_parenthesized, NeedsParentheses, OptionalParentheses, Parentheses,
88
};
99
use crate::prelude::*;
1010

@@ -57,7 +57,14 @@ impl FormatNodeRule<ExprUnaryOp> for FormatExprUnaryOp {
5757
space().fmt(f)?;
5858
}
5959

60-
operand.format().fmt(f)
60+
if operand
61+
.as_bin_op_expr()
62+
.is_some_and(|bin_op| bin_op.op.is_pow())
63+
{
64+
operand.format().with_options(Parentheses::Always).fmt(f)
65+
} else {
66+
operand.format().fmt(f)
67+
}
6168
}
6269

6370
fn fmt_dangling_comments(

crates/ruff_python_formatter/tests/snapshots/black_compatibility@simple_cases__expression.py.snap

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -266,15 +266,6 @@ last_call()
266266
```diff
267267
--- Black
268268
+++ Ruff
269-
@@ -31,7 +31,7 @@
270-
-1
271-
~int and not v1 ^ 123 + v2 | True
272-
(~int) and (not ((v1 ^ (123 + v2)) | True))
273-
-+(really ** -(confusing ** ~(operator**-precedence)))
274-
++really ** -confusing ** ~operator**-precedence
275-
flags & ~select.EPOLLIN and waiters.write_task is not None
276-
lambda arg: None
277-
lambda a=True: a
278269
@@ -115,7 +115,7 @@
279270
arg,
280271
another,
@@ -322,7 +313,7 @@ not great
322313
-1
323314
~int and not v1 ^ 123 + v2 | True
324315
(~int) and (not ((v1 ^ (123 + v2)) | True))
325-
+really ** -confusing ** ~operator**-precedence
316+
+(really ** -(confusing ** ~(operator**-precedence)))
326317
flags & ~select.EPOLLIN and waiters.write_task is not None
327318
lambda arg: None
328319
lambda a=True: a

0 commit comments

Comments
 (0)