When Closure get external variable's value?

Fredrik Lundh fredrik at pythonware.com
Tue Dec 19 10:37:27 EST 2006


Huayang Xia wrote:

> 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.

free variables in an inner scope bind to variables in the outer scope, 
not objects.

if you want to bind to objects, use explicit binding:

     def closureTest(maxIndex=maxIndex):
         return maxIndex

</F>




More information about the Python-list mailing list