diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index f13ee54..e706ca7 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -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.""" diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 4f8037d..21cbc22 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -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],