Skip to content

Commit 9710b82

Browse files
committed
printer: Disambiguate ternary in comprehension condition
1 parent 685e0d0 commit 9710b82

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

src/visitors/printer.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ fn format_subscript(sub: &Subscript) -> String {
439439

440440
fn format_comp(comp: &ComprehensionChunk) -> String {
441441
match *comp {
442-
ComprehensionChunk::If { ref cond } => format!("if {}", format_expr(cond)),
442+
ComprehensionChunk::If { ref cond } => format!("if ({})", format_expr(cond)),
443443
ComprehensionChunk::For { async, ref item, ref iterator } => format!("{}for {} in {}",
444444
if async { "async " } else { "" },
445445
comma_join(item.iter().map(format_expr)),
@@ -671,3 +671,33 @@ fn format_import(imp: &Import) -> String {
671671
}
672672
s
673673
}
674+
675+
#[cfg(test)]
676+
mod tests {
677+
use super::*;
678+
679+
#[test]
680+
fn test_ternary_in_comp_if() {
681+
let e = Expression::ListComp(
682+
Box::new(SetItem::Unique(Expression::Name("a".to_string()))),
683+
vec![
684+
ComprehensionChunk::For {
685+
async: false,
686+
item: vec![Expression::Name("a".to_string())],
687+
iterator: Expression::Name("L".to_string()),
688+
},
689+
ComprehensionChunk::If {
690+
cond: Expression::Ternary(
691+
Box::new(Expression::Call(
692+
Box::new(Expression::Name("f".to_string())),
693+
vec![Argument::Positional(Expression::Name("a".to_string()))],
694+
)),
695+
Box::new(Expression::Name("a".to_string())),
696+
Box::new(Expression::None),
697+
),
698+
},
699+
],
700+
);
701+
assert_eq!(&format_expr(&e), "[a for a in L if ((f(a)) if (a) else (None))]");
702+
}
703+
}

0 commit comments

Comments
 (0)