When Closure get external variable's value?

Huayang Xia huayang.xia at gmail.com
Tue Dec 19 10:27:06 EST 2006


Thanks for the clarification.

But my question is:

When does the closure get the value of the maxIndex in the following
code snippet?

         def testClosure(maxIndex) :

             def closureTest():
                 return maxIndex

             maxIndex += 5

             return closureTest()

         print testClosure(10)


I thought it should be 10 instead of 15. That was wrong.

After several tests, I found maxIndex is, though, local to
testClosure() but is external to the closureTest(). closureTest() gets
the value of maxIndex at run time. So that it's 15 instead of 10. The
following snippet will verify that further:

def testClosure1(lst):

   def closureTest():
      lst.append(lst[-1]+1)

   lst.append(lst[-1]+1)
   return closureTest()

alist = [1]
testClosure1(alist)
alist.append(3)
testClosure1(alist)

The 'lst' in function testClosure1() and the closure closureTest() are
same thing as alist. So everything is dynamic. Variable's value is
determined at run time.




More information about the Python-list mailing list