From this code (which works as you see fit)
my = {} def makefun(fun): def _impl(x): print fun, x return _impl for fun in ["cos", "sin"]: my[fun] = makefun(fun) # will print 'cos' my['cos'](1) fun = 'tan' # will print 'cos' my['cos'](2)
it seems that this is not the namespace of the function definition that decides on the nature of the closure, but instead the namespace of the variables used. Additional tests:
my = dict() fun = '' def makefun(): global fun #This line is switched on or off fun = 'sin' def _impl(x): print fun, x return _impl test = makefun() #gives sin 1 test(1) fun = 'cos' #gives sin 2 if line global fun is used #gives cos 2 if line global fun is NOT used test(2)
So, the correct explanation is that the closure keeps a reference to its arguments, not the value.
source share