From 4754b152a996549e209207ed3b46bb7861d3a47b Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Tue, 12 Jun 2018 11:00:01 -0700 Subject: [PATCH] Allow comprehensions with no looping parts --- hy/compiler.py | 7 +++++++ tests/native_tests/comprehensions.hy | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/hy/compiler.py b/hy/compiler.py index cbe0e30..d6bc53d 100755 --- a/hy/compiler.py +++ b/hy/compiler.py @@ -1094,6 +1094,13 @@ class HyASTCompiler(object): # Compile the parts. if is_for: parts = parts[0] + if not parts: + return Result(expr=ast.parse({ + asty.For: "None", + asty.ListComp: "[]", + asty.DictComp: "{}", + asty.SetComp: "{1}.__class__()", + asty.GeneratorExp: "(_ for _ in [])"}[node_class]).body[0].value) parts = [ Tag(p.tag, self.compile(p.value) if p.tag in ["if", "do"] else [ self._storeize(p.value[0], self.compile(p.value[0])), diff --git a/tests/native_tests/comprehensions.hy b/tests/native_tests/comprehensions.hy index b450e2f..fcd0719 100644 --- a/tests/native_tests/comprehensions.hy +++ b/tests/native_tests/comprehensions.hy @@ -98,6 +98,18 @@ (assert (= (sorted result) answer) (str expr))))) +(defn test-fors-no-loopers [] + + (setv l []) + (for [] (.append l 1)) + (assert (= l [])) + + (assert (= (lfor 1) [])) + (assert (= (sfor 1) #{})) + (assert (= (list (gfor 1)) [])) + (assert (= (dfor [1 2]) {}))) + + (defn test-raise-in-comp [] (defclass E [Exception] []) (setv l [])