Misunderstanding about closures

Michael Geary Mike at DeleteThis.Geary.com
Mon Jun 7 13:12:44 EDT 2004


> > Alexander May wrote:
> >> When I define a function in the body of a loop, why doesn't the
> >> function "close" on the loop vairable?  See example below.

> Michael Geary wrote:
> > Your message title is correct: you're misunderstanding how
> > closures work. :-)
> >
> > BTW, you'll see the same effect in JavaScript or any other
> > language that supports closures.

Alexander Schmolck wrote:
> Not quite. In fact in the language that more or less started it all,
> scheme, the standard iteration construct 'do' does indeed introduce
> a *new binding* on each iteration.

Yeah, there are two separate issues here. It wasn't clear which one Alex M.
was misunderstanding, and I made an assumption about it (always a bad
idea!).

One issue, which I assumed was the problem, has nothing to do with loops,
but with the very nature of closures: What does a closure save, the current
value that a name or variable is bound to, or a reference to that variable?

The other issue is what you're talking about: Does a loop introduce new
bindings on each iteration or not?

To illustrate, here's a variation on Alex's example without the loop:

g = []

def outer():
    x = 1
    def f():
        return x
    g.append( f )
    x = 2
    g.append( f )

outer()
print g[0](), g[1]()

This prints:

2 2

If a closure saved the current value of a variable, it would print:

1 2

Now I am guessing that if you translated this code into any language that
supports closures, including Scheme, you would get the "2 2" result, is that
right? After all, this is pretty much the definition of a closure, that it
saves a reference, not the current value.

If the point of confusion was whether a loop creates new bindings or not,
then my reply was irrelevant--but maybe this discussion will help someone
else understand closures better.

Alex M., now you know the rest of the story... :-)

-Mike





More information about the Python-list mailing list