简体   繁体   English

使用Python装饰器跟踪递归深度

[英]Tracking recursion depth with Python decorators

I am trying to write a decorator that tracks the recursion depth of a recursive function in Python. 我正在尝试编写一个装饰器,以跟踪Python中递归函数的递归深度。

Take, for example, a recursive function such as 以一个递归函数为例


def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

Usually, to track recursion depth you could write something like so 通常,要跟踪递归深度,您可以编写如下内容


    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)

However, after fiddling around with decorators for a while and a lot of googling, I'm not sure this is even possible. 但是,在与装饰者摆弄了一段时间并进行了很多搜索之后,我不确定这是否可能。

I have tried things like 我已经尝试过类似的东西


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)

But it complains that count is an unexpected keyword argument, which I don't really understand because I was under the impression that the wrapper modify replaces all occurrences of fib but I guess not? 但是它抱怨count是一个意外的关键字参数,我不太理解,因为我觉得包装器modify替换所有出现的fib但我猜不是吗?

Pointers would be greatly appreciated. 指针将不胜感激。

You can specify level variable for decorator and then use it in function calls like this: 您可以为装饰器指定级别变量,然后在函数调用中使用它,如下所示:

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

Could you not define the function as the following? 您是否可以定义以下功能?

def fib(n, count=0):
    # ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM