I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.
Something like that:
x = 0
x += 2
testglobal() # should return 2
NameError: name 'x' is not defined
You want to use the
nonlocal statement to access
x, which is not global but local to
def testglobal(): x = 0 def incx(): nonlocal x x += 2 incx() return x assert 2 == testglobal()
The closest you can come to doing this in Python 2 is to replace
x with a mutable value, similar to the argument hack you mentioned in your question.
def testglobal(): x =  def incx(): x += 2 incx() return x assert 2 == testglobal()
Here's an example using a function attribute instead of a list, an alternative that you might find more attractive.
def testglobal(): def incx(): incx.x += 2 incx.x = 0 incx() return inc.x assert 2 == testglobal()