title: Tracking recursion depth with Python decorators
body: <p>I am trying to write a decorator that tracks the recursion depth of a recursive function in Python.</p>
  
  <p>Take, for example, a recursive function such as </p>
  
  <pre><code>
  def fib(n):
      if n == 0:
          return 0
      if n == 1:
          return 1
      else:
          return fib(n-1) + fib(n-2)
  </code></pre>
  
  <p>Usually, to track recursion depth you could write something like so</p>
  
  <pre><code>
      def fib(n, level=0):
          print(level)
          if n == 0:
              return 0
          if n == 1:
              return 1
          else:
              return fib(n-1, level=level+1) + fib(n-2, level=level+1)
  </code></pre>
  
  <p>However, after fiddling around with decorators for a while and a lot of googling, I'm not sure this is even possible.</p>
  
  <p>I have tried things like</p>
  
  <pre><code>
  def visualise(func):
      def modify(*args, **kwargs):
          kwargs["count"] += 1
          print(kwargs["count"])
          return func(*args, **kwargs)
  
      return modify
  
  @visualise
  def fib(n):
      ...
  
  fib(4, count=0)
  </code></pre>
  
  <p>But it complains that <code>count</code> is an unexpected keyword argument, which I don't really understand because I was under the impression that the wrapper <code>modify</code> replaces all occurrences of <code>fib</code> but I guess not?</p>
  
  <p>Pointers would be greatly appreciated.</p>