Skip to content

Commit 684e800

Browse files
[mypyc] feat: extend get_expr_length for enumerate, map, zip, and range
This PR is pretty simple, I just extended get_expr_length to work for a few more obvious cases: - `builtins.enumerate` - `builtins.map` - `builtins.zip` - `builtins.range` This PR is ready for review. Are you going to want tests for all of these? I don't want to spend time now until I know for sure.
1 parent 19697af commit 684e800

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

mypyc/irbuild/for_helpers.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1200,10 +1200,23 @@ def get_expr_length(expr: Expression) -> int | None:
12001200
and expr.node.has_explicit_value
12011201
):
12021202
return len(expr.node.final_value)
1203+
elif isinstance(expr, CallExpr) and isinstance(callee := expr.callee, NameExpr):
1204+
fullname = callee.fullname
1205+
if fullname == "builtins.enumerate" and len(expr.args) == 1:
1206+
return get_expr_length(expr.args[0])
1207+
elif fullname == "builtins.map" and len(expr.args) == 2:
1208+
return get_expr_length(expr.args[1])
1209+
elif fullname == "builtins.zip" and expr.args:
1210+
arg_lengths = [get_expr_length(arg) for arg in expr.args]
1211+
if all(arg is not None for arg in arg_lengths):
1212+
return min(arg_lengths)
1213+
elif fullname == "builtins.range" and all(isinstance(arg, IntExpr) for arg in expr.args):
1214+
return len(range(*(arg.value for arg in expr.args)))
1215+
12031216
# TODO: extend this, passing length of listcomp and genexp should have worthwhile
12041217
# performance boost and can be (sometimes) figured out pretty easily. set and dict
12051218
# comps *can* be done as well but will need special logic to consider the possibility
1206-
# of key conflicts. Range, enumerate, zip are all simple logic.
1219+
# of key conflicts.
12071220
return None
12081221

12091222

0 commit comments

Comments
 (0)