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>Use the <a href="https://docs.python.org/3/reference/simple_stmts.html#nonlocal" rel="nofollow"><code>nonlocal</code></a> statement, so <code>incx</code> will use the <code>x</code> variable from <code>testglobal</code>:</p>

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

testglobal()
</code></pre>

python scope global-variables python-3.5