[Python-Dev] Iteration variables and list comprehensions

Tim Peters tim.one@home.com
Wed, 30 May 2001 16:22:19 -0400


[David Beazley, pretty much repeats why he doesn't like the current scheme]

I hoped it was clear the first time I was at least half sympathetic!  If it
wasn't, I am <wink>.

>> >>> i = 12
>> >>> (lambda: [i**2 for i in range(4)])()
>> [0, 1, 4, 9]
>> >>> i
>> 12
>> >>>
>>
>> That's more like Haskell does it.

> Ah yes, well this is exactly the kind of behavior that seems most
> natural to me.   It's also the behavior that everyone expected went I
> went around to the various Python hackers in the department and asked
> them about it yesterday.

I believe that.

> I suppose I could just write this:
>
>   a = (lambda s: [2*i for i in s])(s)
>
> However, that's pretty ugly.

It's too complicated, isn't it?  In the presence of nested scopes (which are
reality in 2.2),

    a = (lambda: [2*i for i in s])()

does the same thing and is conceptually clearer.  I'm not suggesting that
you actually write that, but view it as a *model* for your intended
semantics.  I wouldn't want to see the implementation actually use a lambda
under the covers, either, but we need some crisp way to explain the intent.
Note that the lambda-trick *model* "does the right thing" for for-loop
targets like x.i and x[i] too.

> In any case, I'm mostly just curious if anyone else has been bitten by
> the problem I've described.  I would certainly love to see a fix for
> it (I would even volunteer to work on a prototype implementation if
> there is interest).

I encourage that, but since it's not 100% backward-compatible you'll enjoy
the usual range of hysterical <wink> opposition.  Needs a PEP, and possibly
even an associated future-statement.  Overall, I'm more in favor of changing
it than not.