What is the maximum recursion depth in Python, and how to increase it?

前端 未结 17 2886
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:14

I have this tail recursive function here:

def recursive_function(n, sum):
    if n < 1:
        return sum
    else:
        return recursive_function(n-1         


        
17条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 05:01

    If you often need to change the recursion limit (e.g. while solving programming puzzles) you can define a simple context manager like this:

    import sys
    
    class recursionlimit:
        def __init__(self, limit):
            self.limit = limit
            self.old_limit = sys.getrecursionlimit()
    
        def __enter__(self):
            sys.setrecursionlimit(self.limit)
    
        def __exit__(self, type, value, tb):
            sys.setrecursionlimit(self.old_limit)
    

    Then to call a function with a custom limit you can do:

    with recursionlimit(1500):
        print(fib(1000, 0))
    

    On exit from the body of the with statement the recursion limit will be restored to the default value.

提交回复
热议问题