Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify bound variables of a closure in Python

Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.

def foo():     var_a = 2     var_b = 3      def _closure(x):         return var_a + var_b + x      return _closure   localClosure = foo()  # Local closure is now "return 2 + 3 + x" a = localClosure(1) # 2 + 3 + 1 == 6  # DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0 # ...but what magic? Is this even possible?  # Local closure is now "return 0 + 3 + x" b = localClosure(1) # 0 + 3 +1 == 4 
like image 222
Vicent Marti Avatar asked Dec 24 '08 23:12

Vicent Marti


1 Answers

It is quite possible in python 3 thanks to the magic of nonlocal.

def foo():         var_a = 2         var_b = 3          def _closure(x, magic = None):                 nonlocal var_a                 if magic is not None:                         var_a = magic                  return var_a + var_b + x          return _closure   localClosure = foo()  # Local closure is now "return 2 + 3 + x" a = localClosure(1) # 2 + 3 + 1 == 6 print(a)  # DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0 localClosure(0, 0)  # Local closure is now "return 0 + 3 + x" b = localClosure(1) # 0 + 3 +1 == 4 print(b) 
like image 84
recursive Avatar answered Sep 28 '22 03:09

recursive