title: Python's nonlocal depends on level of hierarchy?
body: <p>This question is a follow-up on <a href="https://stackoverflow.com/q/370357/923794">a question about Python variable scope</a>. Additional questions <a href="https://stackoverflow.com/q/1261875/923794">q1</a>, <a href="https://stackoverflow.com/q/1414304/923794">q2</a> and <a href="https://stackoverflow.com/questions/2009402/read-write-python-closures/2009899#2009899">answers</a> can be found on SO, among even more.
  The official <a href="http://docs.python.org/release/3.1.3/reference/simple_stmts.html#the-nonlocal-statement" rel="noreferrer">Python documentation</a>, and <a href="http://www.python.org/dev/peps/pep-3104/" rel="noreferrer">PEP 3104</a> are supposed to explain the details, but they don't seem fully self-explanatory to me.</p>
  
  <p>The topic I'm trying to solve is refactoring of code containing <code>nonlocal</code>/<code>global</code> by moving that code up/down one level of hierarchy.</p>
  
  <p>What I do not understand are the implications of this sentence from the Python reference:</p>
  
  <blockquote>
    <p>Names listed in a nonlocal statement, unlike to those listed in a
    global statement, must refer to pre-existing bindings in an enclosing
    scope (the scope in which a new binding should be created cannot be
    determined unambiguously).</p>
  </blockquote>
  
  <p>Given the following code on global scope:
  </p>
  
  <pre><code>var = 0
  def outer():
      global var                  # line A
      var = 1
      def inner():
          nonlocal var            # line B
          var = 2
  
          print('inner:', var)
  
      inner()
      print('outer:', var)
  
  outer()
  print('main:', var)
  </code></pre>
  
  <p>Execution raises an error:</p>
  
  <pre><code>SyntaxError: no binding for nonlocal 'var' found
  </code></pre>
  
  <p>The code works (with different semantics, of course, if either line A is commented out:</p>
  
  <pre><code>inner: 2
  outer: 2
  main: 0
  </code></pre>
  
  <p>or line B is commented out:</p>
  
  <pre><code>inner: 2
  outer: 1
  main: 1
  </code></pre>
  
  <p>However, in the above example, and since <code>nonlocal</code> is supposed to bind var to the "enclosing scope", I would have expected that line A binds the outer/var into global scope and line B then looks for outer/var and also rebinds inner/var to global/var. Instead it seems to not find it at all (due to the rebinding in line A, I suppose) and raise an error.</p>
  
  <p>The desired result I expected was:</p>
  
  <pre><code>inner: 2
  outer: 2
  main: 2
  </code></pre>
  
  <p>Is this just one more example of the confusing state of mind of scoping in Python?</p>
  
  <p>Or, to make this a constructive question:</p>
  
  <ul>
  <li>How can such an example be written in a way that it does not matter at which level a function resides (having to exchange <code>global</code> with <code>nonlocal</code> and vice versa)?</li>
  <li>If the functions reside at an intermediate, and unknown level of hierarchy, how could the author of <code>outer()</code> change the code that neither the outermost (in this case global) level, nor the <code>inner()</code> level have to be touched? - </li>
  </ul>
  
  <p>In my humble understanding of the language, constructs like these (dependecies on closures) are just to be avoided. Others already have suggested to use other language features (<a href="https://stackoverflow.com/questions/2009402/read-write-python-closures/2009474#2009474">classes</a>, <a href="https://stackoverflow.com/questions/2009402/read-write-python-closures/2009575#2009575">func attrs</a>) to achieve this kind of context sensitivity.</p>