title: Refresh decorator
body: <p>I'm trying to write a decorator that 'refreshes' after being called, but where the refreshing only occurs once after the last function exits. Here is an example:</p>
  
  <pre><code>@auto_refresh
  def a():
      print "In a"
  
  @auto_refresh
  def b():
      print "In b"
      a()
  </code></pre>
  
  <p>If <code>a()</code> is called, I want the refresh function to be run after exiting <code>a()</code>. If <code>b()</code> is called, I want the refresh function to be run after exiting <code>b()</code>, but not after <code>a()</code> when called by <code>b()</code>. Here is an example of a class that does this:</p>
  
  <pre><code>class auto_refresh(object):
  
  def __init__(self, f):
  
      print "Initializing decorator"
      self.f = f
  
  def __call__(self, *args, **kwargs):
  
      print "Before function"
      if 'refresh' in kwargs:
          refresh = kwargs.pop('refresh')
      else:
          refresh = False
  
      self.f(*args, **kwargs)
  
      print "After function"
  
      if refresh:
          print "Refreshing"
  </code></pre>
  
  <p>With this decorator, if I run</p>
  
  <pre><code>b()
  print '---'
  b(refresh=True)
  print '---'
  b(refresh=False)
  </code></pre>
  
  <p>I get the following output:</p>
  
  <pre><code>Initializing decorator
  Initializing decorator
  Before function
  In b
  Before function
  In a
  After function
  After function
  ---
  Before function
  In b
  Before function
  In a
  After function
  After function
  Refreshing
  ---
  Before function
  In b
  Before function
  In a
  After function
  After function
  </code></pre>
  
  <p>So when written this way, not specifying the <code>refresh</code> argument means that refresh is defaulted to <code>False</code>. Can anyone think of a way to change this so that <code>refresh</code> is <code>True</code> when not specified? Changing the</p>
  
  <pre><code>refresh = False
  </code></pre>
  
  <p>to </p>
  
  <pre><code>refresh = True
  </code></pre>
  
  <p>in the decorator does <em>not</em> work:</p>
  
  <pre><code>Initializing decorator
  Initializing decorator
  Before function
  In b
  Before function
  In a
  After function
  Refreshing
  After function
  Refreshing
  ---
  Before function
  In b
  Before function
  In a
  After function
  Refreshing
  After function
  Refreshing
  ---
  Before function
  In b
  Before function
  In a
  After function
  Refreshing
  After function
  </code></pre>
  
  <p>because refresh then gets called multiple times in the first and second case, and once in the last case (when it should be once in the first and second case, and not in the last case).</p>