Skip to content

Commit

Permalink
Parenthesize breaking named expressions in match guards
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Jan 5, 2024
1 parent 6dfc1cc commit 2220563
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ def foo():
): # another comment
pass

case {
"long_long_long_key": str(long_long_long_key)
} if value := "long long long long long long long long long long long value":
pass


match pattern_comments:
case (
Expand Down
19 changes: 17 additions & 2 deletions crates/ruff_python_formatter/src/other/match_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ use ruff_python_ast::MatchCase;

use crate::builders::parenthesize_if_expands;
use crate::comments::SourceComment;
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses, Parentheses};
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::{
NeedsParentheses, OptionalParentheses, Parentheses, Parenthesize,
};
use crate::prelude::*;
use crate::statement::clause::{clause_body, clause_header, ClauseHeader};

Expand Down Expand Up @@ -58,7 +61,19 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
}

if let Some(guard) = guard {
write!(f, [space(), token("if"), space(), guard.format()])?;
write!(
f,
[
space(),
token("if"),
space(),
maybe_parenthesize_expression(
guard,
item,
Parenthesize::Optional
)
]
)?;
}

Ok(())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ match long_lines:
): # another comment
pass
case {
"long_long_long_key": str(long_long_long_key)
} if value := "long long long long long long long long long long long value":
pass
match pattern_comments:
case (
Expand Down Expand Up @@ -677,7 +682,9 @@ match newlines:
match long_lines:
case "this is a long line for if condition" if aaaaaaaaahhhhhhhh == 1 and bbbbbbaaaaaaaaaaa == 2: # comment
case "this is a long line for if condition" if (
aaaaaaaaahhhhhhhh == 1 and bbbbbbaaaaaaaaaaa == 2
): # comment
pass
case "this is a long line for if condition with parentheses" if (
Expand All @@ -696,6 +703,11 @@ match long_lines:
): # another comment
pass
case {"long_long_long_key": str(long_long_long_key)} if (
value := "long long long long long long long long long long long value"
):
pass
match pattern_comments:
case (
Expand Down

0 comments on commit 2220563

Please sign in to comment.