title: Python variable scope capture rules
body: <p>I am trying to understand local/global/nonlocal capture rules for python scoping and have encountered some asymmetric behavior, here is an example:</p>
  <pre class="lang-py prettyprint-override"><code>def test():
      i = 0
      d = dict()
      def next():
          d[len(d)] = 'foo' # why is nonlocal d not required?
          nonlocal i # Required to pull 'i' into next.locals()
          i += 1
      while i &lt; 10:
          next()
  
  test()
  </code></pre>
  <p>From the above snippet we have variables <code>d</code> and <code>i</code> declared and defined as <code>dict</code> and <code>int</code> types respectively. However in the nested function <code>next</code> only <code>d</code> can be reached, <code>i</code> requires the <code>nonlocal</code> term to pull <code>i</code> into the function's scope.</p>
  <p>I next theorized that non-referenceable types in python get lifted into the context of it's children's scope.
  However this next example contradicts my theory:</p>
  <pre class="lang-py prettyprint-override"><code>def test2():
      def If():
          return True if qn == None else qn
  
      def Ask():
          nonlocal qn
          qn = i &lt; lim
          return If()
  
      qn = None
      i = 0
      lim = 5
      while i &lt; 10:
          i += 1
          print(i, Ask())
  </code></pre>
  <p>Notice that in <code>test2</code>'s <code>Ask</code> function I do not need to declare <code>nonlocal i</code> and <code>nonlocal lim</code> but require <code>nonlocal qn</code>.</p>
  <p>Is this behavior expected? I would assume either both should require <code>nonlocal</code> or neither would require it.</p>
  <p>Is there a language specification I can reference for similar types of behavior?</p>