Skip to content

Commit

Permalink
Ignore failure to delete list comp variables
Browse files Browse the repository at this point in the history
When iterating over a generator expression `gen` in a list comprehension
`[for x in gen]`, the local variable `x` holds the value of each
generated expression. When the list comprehension is done being
evaluated, the local variable `x` needs to be deleted. This was already
being done. If, however, `gen` is empty, `x` is never defined, and so
deleting it causes an error. This patch adds a check to ignore that
error.
  • Loading branch information
akonradi committed Oct 15, 2023
1 parent 84181df commit 80ea486
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
7 changes: 6 additions & 1 deletion custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1753,7 +1753,12 @@ async def loopvar_scope_restore(self, var_names, save_vars):
if var_name in save_vars:
self.sym_table[var_name] = save_vars[var_name]
else:
del self.sym_table[var_name]
try:
del self.sym_table[var_name]
except KeyError as e:
# If the iterator was empty, the loop variables were never
# assigned to, so deleting them will fail.
pass

async def listcomp_loop(self, generators, elt):
"""Recursive list comprehension."""
Expand Down
2 changes: 2 additions & 0 deletions tests/test_unit_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@
["kw = {'x': 1, 'y': 5}; kw2 = {'z': 10}; {**kw, **kw2}", {"x": 1, "y": 5, "z": 10}],
["[*iter([1, 2, 3])]", [1, 2, 3]],
["{*iter([1, 2, 3])}", {1, 2, 3}],
["[x for x in []]", []],
["[x for x in [] if x]", []],
["if 1: x = 10\nelse: x = 20\nx", 10],
["if 0: x = 10\nelse: x = 20\nx", 20],
["i = 0\nwhile i < 5: i += 1\ni", 5],
Expand Down

0 comments on commit 80ea486

Please sign in to comment.