title: static variable in a function with Python Decorator
body: <p>I was looking for about static value in Python.</p>
  
  <p>And I found <a href="https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function">this</a>.</p>
  
  <pre><code>def static_var(varname, value):
      def decorate(func):
          setattr(func, varname, value)
          return func
      return decorate
  
  @static_var("counter", 0)
  def foo():
      foo.counter += 1
      print "Counter is %d" % foo.counter
  </code></pre>
  
  <p>It is using python decorator for static variable in a function.</p>
  
  <p>The decorator<code>(static_var)</code> initialize static value<code>(foo.counter)</code> before returning the function<code>(foo)</code> decorated.</p>
  
  <p>So I think it should not work as expected, because decorator<code>(static_var)</code> initialize <code>foo.counter</code> every time when <code>foo</code> is called.</p>
  
  <p>As a result, I think if foo() is called two times, it should print <code>1</code> two times  </p>
  
  <pre><code>foo()     
  foo()     
  </code></pre>
  
  <p>But It prints <code>1</code> and <code>2</code>, increasing <code>foo.counter</code></p>
  
  <p>Why...?</p>
  
  <p>Why isn't <code>foo.counter</code> initialized to <code>0</code> every time when foo is called?</p>