title: Difference between closure and decorator in Python
body: <p>This is a program to compute factorial number with cache.</p>
  <pre><code>def run_closure():
      f = cache(factorial)
      print(&quot;5! = %d&quot; % f(5))
      print(&quot;5! = %d&quot; % f(5))
      print(&quot;4! = %d&quot; % f(4))
      pass
  
  
  def run_decorator():
      print(&quot;5! = %d&quot; % factorial(5))
      print(&quot;5! = %d&quot; % factorial(5))
      print(&quot;4! = %d&quot; % factorial(4))
      pass
  
  
  def cache(func):
      table = {}
      def wrapper(n):
          if n in table:
              print(&quot;%d is in memo.&quot; % n)
              return table[n]
          else:
              print(&quot;f(%d) is called.&quot; % n)
              table[n] = func(n)
              return table[n]
      return wrapper
  
  
  # @cache # comment for &quot;run_closure()&quot;; uncomment for &quot;run_decorator&quot; 
  def factorial(n):
      if n == 0:
          return 1
      else:
          return n * factorial(n - 1)
  
  
  def main():
      run_closure()
      # run_decorator()
      pass
  
  if __name__ == &quot;__main__&quot;:
      main()
      pass
  </code></pre>
  <p>I implement this by means of closure and decorator. The former output:</p>
  <blockquote>
  <p>f(5) is called.<br />
  5! = 120<br />
  5 is in memo.<br />
  5! = 120<br />
  f(4) is called.<br />
  4! = 24</p>
  </blockquote>
  <p>The latter output:</p>
  <blockquote>
  <p>f(5) is called.<br />
  f(4) is called.<br />
  f(3) is called.<br />
  f(2) is called.<br />
  f(1) is called.<br />
  f(0) is called.<br />
  5! = 120<br />
  5 is in memo.<br />
  5! = 120<br />
  4 is in memo.<br />
  4! = 24</p>
  </blockquote>
  <p>In the former case, when <code>5!</code> is computed, the previous <code>n!(n&lt;5)</code> should have been computed and saved into <code>table</code> but it didn't. The latter case is what I want. So what's the difference between closure and decorator? Any help is appreciated.</p>