[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Oct 4 05:13:26 CEST 2008

Dillon Collins wrote:

>>   for i in range(3):
>>     let j = str(i):
>>       funs.append(lambda: j)

> Well now, that seems more than a little ridiculous.

I don't think someone coming from Lisp, Scheme or Haskell
would think it ridiculous. The 'let' statement will be
instantly recognisable to them -- unlike your 'scope'
statement, which will be familiar to nobody.

It's true that with a 'let' statement or equivalent,
there's no strict need for a change to the for-loop,
since you can always say

   for i in range(10):
     let i = i:
       funcs.append(lambda: i)

But it's an annoying and odd-looking piece of
boilerplate to have to use, and in that respect is
similar to the existing solutions of inserting another
lambda or using a default argument value.

So as a *convenience*, I'm suggesting that the
for-loop be given automatic let-like behaviour.

> How about C?
> int i;
> int get(void) {return i;}
> int main()
> {
> 	i=3;
> 	get()
> 	i=4;
> }

No, that's not the same thing at all. You're not creating
a closure when i==3 and then calling it after i=4; you're
calling the function while i is still 3.

The claim was that there exist side-effectful languages
with closures that close over values instead of variables.
C can't be one of those, because it doesn't even have


More information about the Python-ideas mailing list