Skip to content

Selecting generator expressions

Generator expressions are a Python construct for lazily producing values. They look like list comprehensions but use parentheses instead of brackets:

python
(x * 2 for x in items)

(gen) selects generator expressions and has the following signature:

clojure
(gen [body?])

Matching any generator expression

The simplest form matches any generator expression:

clojure
(gen)

This matches (x for x in items), (x * 2 for x in range(10) if x > 5), and any other generator expression.

Matching by body

The body parameter refines the selection to generators that yield a specific expression:

clojure
(gen (id x))       ; (x for x in items)
(gen (call len))   ; (len(x) for x in items)

Generator expressions in function calls

In Python, generator expressions can appear in function calls in two ways.

When the generator is the sole argument, no extra parentheses are needed:

python
sum(x for x in items)

Use (gen) directly as the argument selector:

clojure
(call sum (gen))

When the generator is one of multiple arguments, Python requires parentheses:

python
reduce(lambda a,b: a+b, (x for x in items), 0)

Use (arg) to select the generator at a specific position:

clojure
(call reduce (arg 2 (gen)))

Generator expressions vs list comprehensions

(gen) does not match list comprehensions. The following query matches (x for x in items) but not [x for x in items]:

clojure
(gen)

Copyright © 2022-present Semantic Works, Inc.