title: python counter with closure
body: <p>I'm trying to build a counter in python with the property of closure. The code in the following works:</p>
  
  <pre><code>def generate_counter():
      CNT = [0]
      def add_one():
          CNT[0] = CNT[0] + 1
          return CNT[0]
      return add_one
  </code></pre>
  
  <p>However when I change the list CNT to a var, it did not work:</p>
  
  <pre><code>def generate_counter1():
      x = 0
      def add_one():
          x = x + 1
          return x
      return add_one
  </code></pre>
  
  <p>when I print the closure property of an instance, I found the <code>__closure__</code> of the second case is none:</p>
  
  <pre><code>&gt;&gt;&gt; ct1 = generate_counter()
  &gt;&gt;&gt; ct2 = generate_counter1()
  &gt;&gt;&gt; print(ct1.__closure__[0])
  &lt;cell at 0xb723765c: list object at 0xb724370c&gt;
  &gt;&gt;&gt; print(ct2.__closure__)
  None
  </code></pre>
  
  <p>Just wondering why the index in outer function has to be a list?</p>
  
  <hr>
  
  <p>Thanks for the answers! Found the docs which clearly explained this problem
  <a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="noreferrer">https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value</a></p>