title: Python nonlocal statement in a class definition
body: <p>I'm trying to perform some analysis of scope in Python 3 source code and I'm stuck with how the nonlocal statement statement works inside a class definition.</p>
  
  <p>As I understand it, the class definition executes its body inside a new namespace (call it dict) and binds the class name to the result of type(name, bases, dict). Nonlocal x should work as long as it refers to a variable that is bound somewhere in the enclosing non-local scope.</p>
  
  <p>From this I expect the following code to compile and run:</p>
  
  <pre><code>class A:
      v = 1
      class B:
          nonlocal v
          v = 2
  </code></pre>
  
  <p>but this fails with</p>
  
  <pre><code>SyntaxError: no binding for nonlocal 'v' found
  </code></pre>
  
  <p>while the following code runs perfectly</p>
  
  <pre><code>def A():
      v = 1
      class B:
          nonlocal v
          v = 2
  </code></pre>
  
  <p>Can anyone explain the difference here between the closure of the function definition and the class definition?</p>