In python, I can write :
def func():
x = 1
print x
x+=1
def _func():
print x
return _func
test = func()
test()
You can't rebind variables that are closed over in Python 2 (you can use nonlocal
in Python 3). If I have to do what you're doing in Python 2 then I do the following workaround:
class Pointer(object):
def __init__(self, val):
self.val = val
def func():
px = Pointer(1)
print px.val
px.val += 1
def _func():
print px.val
return _func
test = func()
test()
Basically I put whatever values I need to be mutated onto an object - sometimes I use a list with one element - and then re-write the code so that all that happens is method calls. The above is actually equivalent to:
class Pointer(object):
def __init__(self, val):
self.val = val
def func():
px = Pointer(1)
print px.val
px.__setattr__('val', px.val + 1)
def _func():
print px.val
return _func
test = func()
test()