Skip to content

Commit daabadd

Browse files
[mypyc] feat: try constant_fold_expr in translate_f_string
1 parent c2a82b9 commit daabadd

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

mypyc/irbuild/specialize.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -746,26 +746,33 @@ def translate_fstring(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Va
746746
and expr.arg_kinds == [ARG_POS]
747747
and isinstance(expr.args[0], ListExpr)
748748
):
749-
for item in expr.args[0].items:
749+
items = expr.args[0].items
750+
for i, item in enumerate(items):
750751
if isinstance(item, StrExpr):
751752
continue
753+
elif isinstance(folded := constant_fold_expr(builder, item), str):
754+
items[i] = StrExpr(folded)
755+
continue
752756
elif isinstance(item, CallExpr):
753-
if not isinstance(item.callee, MemberExpr) or item.callee.name != "format":
754-
return None
755-
elif (
756-
not isinstance(item.callee.expr, StrExpr) or item.callee.expr.value != "{:{}}"
757+
if not (
758+
isinstance(callee := item.callee, MemberExpr)
759+
and callee.name == "format"
760+
and isinstance(callee.expr, StrExpr)
761+
# TODO: extend this to cover {!r:{}}
762+
and callee.expr.value == "{:{}}"
757763
):
758764
return None
759765

760-
if not isinstance(item.args[1], StrExpr) or item.args[1].value != "":
766+
format_spec = item.args[1]
767+
if not isinstance(format_spec, StrExpr) or format_spec.value != "":
761768
return None
762769
else:
763770
return None
764771

765772
format_ops = []
766773
exprs: list[Expression] = []
767774

768-
for item in expr.args[0].items:
775+
for item in items:
769776
if isinstance(item, StrExpr) and item.value != "":
770777
format_ops.append(FormatOp.STR)
771778
exprs.append(item)

0 commit comments

Comments
 (0)