title: Python - Function attributes or mutable default values
body: <p>Say you have a function that needs to maintain some sort of state and behave differently depending on that state.  I am aware of two ways to implement this where the state is stored entirely by the function:</p>
  
  <ol>
  <li>Using a function attribute</li>
  <li>Using a mutable default value</li>
  </ol>
  
  <p>Using a slightly modified version of <a href="https://stackoverflow.com/questions/7182546/how-to-replace-the-nth-appearance-of-a-needle-in-a-haystack-python/7182712#7182712">Felix Klings answer to another question</a>, here is an example function that can be used in <code>re.sub()</code> so that only the third match to a regex will be replaced:</p>
  
  <p>Function attribute:</p>
  
  <pre><code>def replace(match):
      replace.c = getattr(replace, "c", 0) + 1
      return repl if replace.c == 3 else match.group(0)
  </code></pre>
  
  <p>Mutable default value:</p>
  
  <pre><code>def replace(match, c=[0]):
      c[0] += 1
      return repl if c[0] == 3 else match.group(0)
  </code></pre>
  
  <p>To me the first seems cleaner, but I have seen the second more commonly.  Which is preferable and why?</p>