title: Global variables in embedded functions
body: <p>I have the following snippet:</p>
  
  <pre><code>def test ():
    num_sum = 0
    def inner_test ():
      global num_sum
      num_sum += 1
    inner_test()
  return num_sum
  </code></pre>
  
  <p>When I run test() I get:</p>
  
  <blockquote>
    <p>NameError: name 'num_sum' is not defined</p>
  </blockquote>
  
  <p>I was expecting that the inner function would change the value of the <code>num_sum</code> variable defined in the outer function. Basically, I need a global variable to increment in an inner function which I may call recursively. </p>
  
  <p>I noticed that this pattern works well with collections (lists, dictionaries) even if I don't define the variable as global (but pass it as a parameter to the inner function). </p>
  
  <p>However, with scalar values like <code>int</code> this pattern seems to break. Neither defining the variable as global (as is here) nor passing it as a parameter to the inner function works as intended. Basically, the scalar variable stays unchanged. What do I need to do to get the desired behaviour with such scalar values?</p>