Omit tuple parentheses inside comprehensions (#5790)

This commit is contained in:
Chris Pryer 2023-07-19 08:05:38 -04:00 committed by GitHub
parent 38678142ed
commit 9fb8d6e999
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 198 additions and 42 deletions

View file

@ -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),
},

View file

@ -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),
}
}
}