Skip to content

Commit 987406d

Browse files
committed
added list comprehension
1 parent 8d1a661 commit 987406d

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

custom_components/pyscript/eval.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,26 @@ async def ast_list(self, arg):
981981
if isinstance(arg.ctx, ast.Load):
982982
return await self.eval_elt_list(arg.elts)
983983

984+
async def listcomp_loop(self, generators, elt):
985+
"""Recursive list comprehension."""
986+
out = []
987+
gen = generators[0]
988+
for loop_var in await self.aeval(gen.iter):
989+
await self.recurse_assign(gen.target, loop_var)
990+
for cond in gen.ifs:
991+
if not await self.aeval(cond):
992+
break
993+
else:
994+
if len(generators) == 1:
995+
out.append(await self.aeval(elt))
996+
else:
997+
out += await self.listcomp_loop(generators[1:], elt)
998+
return out
999+
1000+
async def ast_listcomp(self, arg):
1001+
"""Evaluate list comprehension."""
1002+
return await self.listcomp_loop(arg.generators, arg.elt)
1003+
9841004
async def ast_tuple(self, arg):
9851005
"""Evaluate Tuple."""
9861006
return tuple(await self.eval_elt_list(arg.elts))

tests/custom_components/pyscript/test_unit_eval.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,33 @@
178178
["import random as rand, math as m\n[rand.uniform(10,10), m.sqrt(1024)]", [10, 32]],
179179
["import cmath\ncmath.sqrt(complex(3, 4))", 2 + 1j],
180180
["from math import sqrt as sqroot\nsqroot(1024)", 32],
181+
["[i for i in range(7) if i != 5 if i != 3]", [0, 1, 2, 4, 6]],
182+
[
183+
"""
184+
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
185+
[val for sublist in matrix for val in sublist if val != 8]
186+
""",
187+
[1, 2, 3, 4, 5, 6, 7, 9],
188+
],
189+
[
190+
"""
191+
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
192+
[val for sublist in matrix if sublist[0] != 4 for val in sublist if val != 8]
193+
""",
194+
[1, 2, 3, 6, 7, 9],
195+
],
196+
[
197+
"""
198+
# check short-circuit of nested if
199+
cnt = 0
200+
def no_op(i):
201+
global cnt
202+
cnt += 1
203+
return i
204+
[i for i in range(7) if no_op(i) != 5 if no_op(i) != 3] + [cnt]
205+
""",
206+
[0, 1, 2, 4, 6, 13],
207+
],
181208
[
182209
"""
183210
d = {"x": 1, "y": 2, "z": 3}

0 commit comments

Comments
 (0)