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>You want to use the <code>nonlocal</code> statement to access <code>x</code>, which is not global but local to <code>testglobal</code>.</p>

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

<p>The closest you can come to doing this in Python 2 is to replace <code>x</code> with a mutable value, similar to the argument hack you mentioned in your question.</p>

<pre><code>def testglobal():
  x = [0]
  def incx():
    x[0] += 2
  incx()
  return x[0]
assert 2 == testglobal()
</code></pre>

<p>Here's an example using a function attribute instead of a list, an alternative that you might find more attractive.</p>

<pre><code>def testglobal():
  def incx():
    incx.x += 2
  incx.x = 0
  incx()
  return inc.x
assert 2 == testglobal() 
</code></pre>

python scope global-variables python-3.5