Python share global variable only for functions inside of function
<p>I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.</p>

<p>Something like that:</p>

<pre><code>def testglobal():
  x = 0
  def incx():
    global x
    x += 2
  incx()
  return x
testglobal() # should return 2
</code></pre>

<p>However, I'm getting error <code>NameError: name 'x' is not defined</code></p>

<p>There is hacky solution to make list and use first value of that list as <code>x</code>. But this is so ugly.</p>

<p>So how can I share <code>x</code> with <code>incx</code> function ? Or should I use completely different approach ?</p>

<p>This will work unless you are still using Python 2.x:</p>

<pre><code>def testglobal():
  x = 0
  def incx():
    nonlocal x
    x += 2
  incx()
  return x

testglobal() # should return 2
</code></pre>

<p>Possible a cleaner solution though would be to define a class to store your state between method calls.</p>

python scope global-variables python-3.5