Skip to content

Commit b67f10a

Browse files
committed
feat: implement constant folding for str.format
1 parent e84c21c commit b67f10a

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

mypy/constant_fold.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,22 +77,34 @@ def constant_fold_expr(expr: Expression, cur_mod_id: str) -> ConstantValue | Non
7777
value = constant_fold_expr(expr.expr, cur_mod_id)
7878
if value is not None:
7979
return constant_fold_unary_op(expr.op, value)
80-
# --- partial str.join support in preparation for f-string constant folding ---
80+
# --- f-string requires partial support for both str.join and str.format ---
8181
elif (
8282
isinstance(expr, CallExpr)
8383
and isinstance(callee := expr.callee, MemberExpr)
8484
and isinstance(folded_callee := constant_fold_expr(callee.expr, cur_mod_id), str)
85-
and callee.name == "join"
86-
and len(args := expr.args) == 1
87-
and isinstance(arg := args[0], (ListExpr, TupleExpr))
8885
):
89-
folded_items = []
90-
for item in arg.items:
91-
val = constant_fold_expr(item, cur_mod_id)
92-
if not isinstance(val, str):
93-
return None
94-
folded_items.append(val)
95-
return folded_callee.join(folded_items)
86+
# --- partial str.join constant folding ---
87+
if (
88+
callee.name == "join"
89+
and len(args := expr.args) == 1
90+
and isinstance(arg := args[0], (ListExpr, TupleExpr))
91+
):
92+
folded_items: list[str] = []
93+
for item in arg.items:
94+
val = constant_fold_expr(item, cur_mod_id)
95+
if not isinstance(val, str):
96+
return None
97+
folded_items.append(val)
98+
return folded_callee.join(folded_items)
99+
# --- str.format constant folding
100+
elif callee.name == "format":
101+
folded_args: list[str] = []
102+
for arg in expr.args:
103+
arg_val = constant_fold_expr(arg, cur_mod_id)
104+
if arg_val is None:
105+
return None
106+
folded_args.append(arg_val)
107+
return folded_callee.format(*folded_args)
96108
return None
97109

98110

0 commit comments

Comments
 (0)