Selecting generator expressions
Generator expressions are a Python construct for lazily producing values. They look like list comprehensions but use parentheses instead of brackets:
(x * 2 for x in items)(gen) selects generator expressions and has the following signature:
(gen [body?])Matching any generator expression
The simplest form matches any generator expression:
(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:
(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:
sum(x for x in items)Use (gen) directly as the argument selector:
(call sum (gen))When the generator is one of multiple arguments, Python requires parentheses:
reduce(lambda a,b: a+b, (x for x in items), 0)Use (arg) to select the generator at a specific position:
(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]:
(gen)