learning to use iterators

Ben Finney ben+python at benfinney.id.au
Tue Dec 23 16:25:45 EST 2014


Ian Kelly <ian.g.kelly at gmail.com> writes:

> On Tue, Dec 23, 2014 at 11:55 AM, Seb <spluque at gmail.com> wrote:
> > Particulary, what do the parentheses do there?
>
> The parentheses enclose a generator expression, which is similar to a
> list comprehension [1] but produce a generator, which is a type of
> iterator, rather than a list.

To be clear: there's nothing about parentheses that produce a generator
expression. Rather, parentheses are just performing their typical role
of enclosing an expression.

The generator expression is produced by the syntax used, such as
‘frob(spam) for spam in collection_of_spam if spam > 0’. The surrounding
parentheses don't affect that; they are not part of the generator
syntax. They *do* enclose it so the Python parser knows it is an
expression distinct from what surrounds it.

For this reason, if you already have some syntax where it will be clear
what is a distinct expression, additional parentheses are not needed. In
other words, parentheses are only needed to *separate* a generator
expression from its surrounds.

    # Syntax would be ambiguous without parentheses.
    foo = (frob(spam) for spam in collection_of_spams if spam > 0)

    # Syntax already dictates the parameter is an expression;
    # no additional parens needed.
    twiddle(frob(spam) for spam in collection_of_spams if spam > 0)

Parens are used in a lot of places, but they are commonly not *part of*
the expression; rather, they enclose the expression to be unambiguous.

-- 
 \          “Any sufficiently advanced bug is indistinguishable from a |
  `\                                          feature.” —Rich Kulawiec |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list