One way to do this in py2x is to pass the variable itself to the internal method, in py3x
this has been fixed and you can use nonlocal
statement there.
The error is raised because functions are objects too and are evaluated during their definition, and during definition as soon as python sees i += 1
(which is equivalent to i = i + 1
) it thinks that i
is a local variable inside that function. But, when the function is actually called it fails to find any value for the i
(on the RHS ) locally and thus the error is raised.
def method1():
i = 0
def _method1(i):
i += 1
print 'i=', i
return i #return the updated value
i=_method1(i) #update i
print i
method1()
or use a function attribute:
def method1():
method1.i = 0 #create a function attribute
def _method1():
method1.i += 1
print 'i=', method1.i
_method1()
method1()
For py3x:
def method1():
i =0
def _method1():
nonlocal i
i += 1
print ('i=', i)
_method1()
method1()