[Python-Dev] PEP 289 - Generator Expressions - Let's Move Forward

Armin Rigo arigo at tunes.org
Fri Apr 30 09:07:00 EDT 2004


Hello,

On Fri, Apr 30, 2004 at 05:16:32AM -0700, Guido van Rossum wrote:
> Thanks for the analysis.  My comment on this: why on earth would you
> want to replace the perfectly sensible list comprehension with a
> generator comprehension in this particular case?

I was using this example more generally to show that if you have a
late-binding genexpr, you have to worry about not changing the local variables
it uses, which looks like all uses of genexprs with free variables are subtle
bugs waiting to appear whenever someone modifies the function anywhere after
the genexpr.  The same argument applies to the other stdlib cases I mentioned
(which make somewhat less than 10% of all uses).

The alternative -- actively using the late-binding aspect -- would lead to
code in which you have to worry about which values the local variables have at
the moment the next element is fetched from the iterator.  For example:

    x_square = (x*x for i in itertools.repeat(None)).next
    ...
    x = 5
    print x_square()    # 25
    x = 6
    print x_square()    # 36

This looks (a) cool and (b) a complete hack that nobody should be allowed to
do without messing with sys._getframe().


A bientôt,

Armin.




More information about the Python-Dev mailing list