title: Python - decorator calling inner function?
body: <p>I'm currently trying out decorators and I can't understand one thing. I have simple decorator:</p>
  
  <pre><code>def new_decorator(func):
      print "Calling new_decorator()"
      def wrap(arg):
          print "Calling wrap()"
          func(arg)
      return wrap  
  
  @new_decorator
  def foo(name):
      print name
  </code></pre>
  
  <p>Upon running we get:</p>
  
  <pre><code>'Calling decorate()' 
  </code></pre>
  
  <p>Only after calling <code>foo</code>:</p>
  
  <pre><code>&gt;&gt;&gt; foo('Jon')
  Calling wrap()
  Jon
  </code></pre>
  
  <p>Till now I understand everything (I think). <code>new_decorator(func)</code> is called at the start, with <code>foo</code> as parameter and it returns <code>wrap</code>. But now I tried decorators with parameters: </p>
  
  <pre><code>def add_attr(varname, value):
      def decorate(func):
          print "Calling decorate()"
          setattr(func, varname, value)
          return func
      return decorate
  
  @add_attr('var', 'New attribute')
  def foo():
      print "Calling foo()"
      print foo.var
  </code></pre>
  
  <p>When running it (without calling <code>foo()</code>) it returns:</p>
  
  <pre><code>'Calling decorate()'
  </code></pre>
  
  <p>After <code>foo()</code>:</p>
  
  <pre><code>&gt;&gt;&gt; foo()
  Calling foo()
  New attribute
  </code></pre>
  
  <p>What I can't understand is, <strong>why this "inner" function <code>decorate</code> is called</strong> at the start, before even calling <code>foo</code>? In first example it wasn't. And how was function <code>foo</code> send as a parameter to <code>decorate</code>? <code>add_attr</code> gets only 2 parameters, and neither of them is <code>foo</code>.</p>