title: In Python 2, how do I write to variable in the parent scope?
body: <p>I have some code like:</p>
  <pre><code>def example():
      # other logic omitted
  
      stored_blocks = {}
      def replace_blocks(m):
          block = m.group(0)
          block_hash = sha1(block)
          stored_blocks[block_hash] = block
          return '{{{%s}}}' % block_hash
  
      num_converted = 0
      def convert_variables(m):
          name = m.group(1)
          num_converted += 1
          return '&lt;%%= %s %%&gt;' % name
  
      fixed = MATCH_DECLARE_NEW.sub('', template)
      fixed = MATCH_PYTHON_BLOCK.sub(replace_blocks, fixed)
      fixed = MATCH_FORMAT.sub(convert_variables, fixed)
  
      # more logic...
  </code></pre>
  <p>Adding elements to <code>stored_blocks</code> works fine, but I cannot increase <code>num_converted</code> in the second nested function. I get an exception that says <code>UnboundLocalError: local variable 'num_converted' referenced before assignment</code>.</p>
  <p>I know that in 3.x, I could try <code>nonlocal num_converted</code>, but how can I solve the problem in 2.x? I don't want to use a global variable for this.</p>