Skip to content

Commit

Permalink
Add parentheses if expression breaks
Browse files Browse the repository at this point in the history
  • Loading branch information
cnpryer committed Aug 26, 2023
1 parent 004b340 commit e2b6f04
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
11 changes: 7 additions & 4 deletions crates/ruff_python_formatter/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,13 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
if format_expression.inspect(f)?.will_break() {
// The group here is necessary because `format_expression` may contain IR elements
// that refer to the group id
group(&format_expression)
.with_group_id(Some(group_id))
.should_expand(true)
.fmt(f)
group(&format_args![
text("("),
soft_block_indent(&format_expression),
text(")")
])
.with_group_id(Some(group_id))
.fmt(f)
} else {
// Only add parentheses if it makes the expression fit on the line.
// Using the flat version as the most expanded version gives a left-to-right splitting behavior
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ async def main():
```diff
--- Black
+++ Ruff
@@ -21,7 +21,9 @@
@@ -21,11 +21,15 @@
# Check comments
async def main():
Expand All @@ -103,6 +103,13 @@ async def main():
+ )
async def main():
- await asyncio.sleep(1) # Hello
+ await (
+ asyncio.sleep(1) # Hello
+ )
async def main():
```

Expand Down Expand Up @@ -138,7 +145,9 @@ async def main():
async def main():
await asyncio.sleep(1) # Hello
await (
asyncio.sleep(1) # Hello
)
async def main():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,9 @@ d13 = (
)
# Doesn't fit, default
d2 = x.e().esadjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkfsdddd() #
d2 = (
x.e().esadjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkfsdddd() #
)
# Doesn't fit, fluent style
d3 = (
Expand Down

0 comments on commit e2b6f04

Please sign in to comment.