[Python-Dev] namespace for generator expressions

Phillip J. Eby pje at telecommunity.com
Mon Jan 26 21:10:09 EST 2004

At 07:51 PM 1/26/04 -0500, Jeremy Hylton wrote:
>On Mon, 2004-01-26 at 17:36, Phillip J. Eby wrote:
> > The intent is that listcomps should be "safely" replaceable with genexprs
> > anywhere that an iterator is acceptable in place of a list.
> >
> > >How often is a generator expression not going to be evaluated almost
> > >immediately? I guess, when they're passed to a function. But even in that
> > >case, how often are the bindings going to change? Except in pathological
> > >cases, they won't.
> >
> > A trivial example is:
>Are there non-trivial examples?  The PEP suggests that they exist, but
>doesn't provide any.


I'd have posted a link to this first, but it took a while to track it down.

> > iterators = []
> > for i in range(5):
> >      iterators.append(x*2 for x in range(i))
> >
> > print map(list,iterators)
> >
> > If a listcomp is used, you get:
> >
> > [[],[0,],[0,2],[0,2,4],[0,2,4,6],[0,2,4,6,8]]
> >
> > If genexprs do late binding, you get:
> >
> > [[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8],[0,2,4,6,8]]
>Note that Armin Rigo suggested a small change here a few weeks ago that
>makes the list comp and the gen expr behave the same way.

It's a start, but it doesn't address Tim's example.

>BTW is there good terminology for describing the parts of a list comp or
>gen expr?  How about the iterator, the conditions, and the expression?

Sounds good to me.  My contrived example demonstrated early binding for the 
iterator.  Tim's shows early binding for the conditions.  I think it's also 
straightforward to see that early binding for the expression is similarly 

If you're looking for more arguments, I'd suggest looking at all of Tim 
Peters' posts for October under the subject "accumulator display syntax".  :)

More information about the Python-Dev mailing list