Skip to content Skip to sidebar Skip to footer

Tracking Recursion Depth With Python Decorators

I am trying to write a decorator that tracks the recursion depth of a recursive function in Python. Take, for example, a recursive function such as def fib(n): if n == 0:

Solution 1:

You can specify level variable for decorator and then use it in function calls like this:

defvisualise(func):
     visualise.level = 0defwrapper(*args, **kwargs):
         print("In:", visualise.level)
         visualise.level += 1
         result = func(*args, **kwargs)
         visualise.level -= 1print("Out:", visualise.level)
         return result
     return wrapper

Solution 2:

Here's a class based approach of the previous answer from Lev Zakharov above

from functools import wraps
classVisualize(object):
    def__init__(self):
        self.level = 0def__call__(self, func):
        @wraps(func)defwrapper(*args, **kwargs):
            print("In:", self.level)
            self.level += 1
            result = func(*args, **kwargs)
            self.level -= 1print("Out:", self.level)
            return result
        return wrapper

@Visualize()deffib(n):
...

About @wraps see here

Solution 3:

Could you not define the function as the following?

deffib(n, count=0):
    # ....

Post a Comment for "Tracking Recursion Depth With Python Decorators"