@@ -439,7 +439,7 @@ fn format_subscript(sub: &Subscript) -> String {
439
439
440
440
fn format_comp ( comp : & ComprehensionChunk ) -> String {
441
441
match * comp {
442
- ComprehensionChunk :: If { ref cond } => format ! ( "if {} " , format_expr( cond) ) ,
442
+ ComprehensionChunk :: If { ref cond } => format ! ( "if ({}) " , format_expr( cond) ) ,
443
443
ComprehensionChunk :: For { async, ref item, ref iterator } => format ! ( "{}for {} in {}" ,
444
444
if async { "async " } else { "" } ,
445
445
comma_join( item. iter( ) . map( format_expr) ) ,
@@ -671,3 +671,33 @@ fn format_import(imp: &Import) -> String {
671
671
}
672
672
s
673
673
}
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