Zen of Python

Nick Coghlan ncoghlan at iinet.net.au
Fri Jan 21 08:47:50 EST 2005


Paul Rubin wrote:
> You snipped out the examples I gave, like [x*x for x in range(5)]
> leaving unnecessary residue in the name space.  Was it not obvious
> from the beginning that that was a kludge?  If it was obviously
> a kludge, was it not obvious that there would be reason to want to
> fix it someday?  I'm saying that if some new feature is going to
> need a fix later, it's better to fix it before releasing it in
> the first place.

The scoping problem isn't the the least bit obvious, since the equivalent for 
loop also happens at local scope:

Py> lst = []
Py> for x in range(5):
...   lst.append(x*x)
...
Py> print x
4
Py> lst2 = [y*y for y in range(5)]
Py> print y
4

However experience has shown that while having the iteration variable visible 
after a for loop is useful (due to the existence of the break and raise 
statements), with a list comprehension the identical behaviour is nothing more 
than namespace pollution (since you can't use list comprehensions for alternate 
control flow based searches).

So Python 2.4's generator expressions are quite happily evaluated in a separate 
frame, and the fact that the iteration variable is hidden from the containing 
scope is viewed as a feature.

But knowing a priori that copying the for loop semantics exactly would turn out 
to be a misfeature? I'll go with Steve's assessment of psychic powers ;)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list