Skip to content

Commit e85beaf

Browse files
committed
make simple f-strings work
1 parent 6f2eea2 commit e85beaf

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/unparser.rs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -876,18 +876,38 @@ impl Unparser {
876876

877877
fn unparse_expr_formatted_value(&mut self, node: &ExprFormattedValue<TextRange>) {
878878
// TODO
879-
self.write_str("{ ");
880-
self.unparse_expr(&node.value);
879+
self.write_str("{");
880+
let mut inner_unparser = Unparser::new();
881+
inner_unparser.unparse_expr(&node.value);
882+
let inner_expr = inner_unparser.source.as_str();
883+
if inner_expr.starts_with("{") {
884+
self.write_str(" ");
885+
}
886+
self.write_str(inner_expr);
881887

882888
if let Some(format_spec) = &node.format_spec {
883889
self.write_str(":");
884890
self.unparse_expr(format_spec);
885891
}
886-
self.write_str(" }");
892+
self.write_str("}");
887893
}
888894

889-
fn unparse_expr_joined_str(&mut self, _node: &ExprJoinedStr<TextRange>) {
890-
// TODO
895+
fn unparse_expr_joined_str(&mut self, node: &ExprJoinedStr<TextRange>) {
896+
self.write_str("f");
897+
898+
for (index, expr) in node.values.iter().enumerate() {
899+
let mut inner_unparser = Unparser::new();
900+
inner_unparser.unparse_expr(expr);
901+
let mut expr_source = inner_unparser.source.as_str();
902+
if index > 0 {
903+
expr_source = expr_source.trim_start_matches("\"")
904+
}
905+
906+
if index != node.values.len() - 1 {
907+
expr_source = expr_source.trim_end_matches("\"")
908+
}
909+
self.write_str(&expr_source);
910+
}
891911
}
892912

893913
fn _unparse_constant(&mut self, constant: &Constant) {

test_files/simple_f_string.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
world = "World"
3+
if __name__ == "__main__":
4+
print(f"Hello {world}!")

0 commit comments

Comments
 (0)