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

Dillon Collins dillonco at comcast.net
Sat Oct 4 03:00:22 CEST 2008

On Friday 03 October 2008, Greg Ewing wrote:
> My next step would be to propose a 'let' statement
> for dealing with things like that:
>    for i in range(3):
>      let j = str(i):
>        funs.append(lambda: j)
> The 'let' statement would do the same thing for its
> variable as the for-loop, but in a one-off fashion.

Well now, that seems more than a little ridiculous.  If we're going to be 
creating a keyword that rescopes variables, why not just use that instead of 
messing with the for loop.  Seems like that would be a generally more useful 
solution anyway.

Perhaps instead:

for i in range(10):
    j = str(i)
    scope i, j:
        funs.append(lambda: (j,i))

> > Some of those languages can bind the variable value early, so if
> >
> > you were to write the equivalent of:
> >     >>> i= 3
> >     >>> f= lambda: i
> >     >>> i= 4
> Can you give me an example of an imperative language that
> behaves that way? I don't think I've ever seen one.
> (Note that the above would be illegal in any functional
> (i.e. side-effect-free) language, since the syntax doesn't
> allow you to express rebinding an existing variable.)

How about C?

int i;
int get(void) {return i;}

int main()

I think the confusion is the fact that the a local scope is effectively a 
_global_ scope in locally defined functions.  It's really a rather 
conceptually elegant setup, though a tad confusing.  Perhaps that's because 
we're used to seeing globals as "the global scope" rather than "all 
encompassing scopes".

More information about the Python-ideas mailing list