mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-23 04:55:09 +00:00
Omit tuple parentheses inside comprehensions (#5790)
This commit is contained in:
parent
38678142ed
commit
9fb8d6e999
7 changed files with 198 additions and 42 deletions
|
@ -14,6 +14,9 @@ use crate::prelude::*;
|
|||
|
||||
#[derive(Eq, PartialEq, Debug, Default)]
|
||||
pub enum TupleParentheses {
|
||||
/// Black omits parentheses for tuples inside of comprehensions.
|
||||
Comprehension,
|
||||
|
||||
/// Effectively `None` in `Option<Parentheses>`
|
||||
#[default]
|
||||
Default,
|
||||
|
@ -116,6 +119,13 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
|
|||
parenthesized("(", &ExprSequence::new(item), ")").fmt(f)
|
||||
}
|
||||
_ => match self.parentheses {
|
||||
TupleParentheses::Comprehension => {
|
||||
let separator =
|
||||
format_with(|f| group(&format_args![text(","), space()]).fmt(f));
|
||||
f.join_with(separator)
|
||||
.entries(elts.iter().formatted())
|
||||
.finish()
|
||||
}
|
||||
TupleParentheses::Subscript => group(&ExprSequence::new(item)).fmt(f),
|
||||
_ => parenthesize_if_expands(&ExprSequence::new(item)).fmt(f),
|
||||
},
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
use crate::comments::{leading_comments, trailing_comments};
|
||||
use crate::expression::expr_tuple::TupleParentheses;
|
||||
use crate::prelude::*;
|
||||
use crate::AsFormat;
|
||||
use crate::{FormatNodeRule, PyFormatter};
|
||||
|
@ -58,7 +59,7 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
|
|||
trailing_comments(before_target_comments),
|
||||
group(&format_args!(
|
||||
Spacer(target),
|
||||
target.format(),
|
||||
ExprTupleWithoutParentheses(target),
|
||||
in_spacer,
|
||||
leading_comments(before_in_comments),
|
||||
text("in"),
|
||||
|
@ -104,3 +105,17 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
|
|||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct ExprTupleWithoutParentheses<'a>(&'a Expr);
|
||||
|
||||
impl Format<PyFormatContext<'_>> for ExprTupleWithoutParentheses<'_> {
|
||||
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
|
||||
match self.0 {
|
||||
Expr::Tuple(expr_tuple) => expr_tuple
|
||||
.format()
|
||||
.with_options(TupleParentheses::Comprehension)
|
||||
.fmt(f),
|
||||
other => other.format().fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue