Suppose there is a function that collects data, for example from Wikipedia, the function runs itself recursively, the default recursion limit is 2000, but this is not enough for data collection, and I need the function to run a lot more times, what are the outputs?

sys.setrecursionlimit(1500) 

You can raise the limit, but this will lead to a stack overflow (this is such protection in the CPython implementation), and if the limit is raised above 4,000, the interpreter does not stand up. Actually, it is clear that I can solve the problem without a recursive start, but I wonder if it is possible to do something with recursion, so that the function could call itself 100,000 times like that?

2 answers 2

You can also look at your algorithm and:

  1. Increase the stack, as suggested in the comments.
  2. Still use a non-recursive algorithm.
  3. See if your algorithm can be implemented using tail recursion and if tailor recursion optimization is supported by the CPython interpreter.
  • Out of the box - does not support and will not support, somewhere there was even an official response from Guido about it. - insolor
  • * Upnul for 3rd item. I think tail recursion is the optimal candidate for a solution, especially since OP has its own code. * To @insolor comment: out of the box is not out of the box, but finding a ready-made solution to support tail recursion is not a problem, for example, Google knows about this * and here is the question about tail recursion in python in English. stackoverflow - Roman Bortnikov

Resolved in this way:

 class recursion(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): result = self.func(*args, **kwargs) while callable(result): result = result() return result def call(self, *args, **kwargs): return lambda: self.func(*args, **kwargs) @recursion def foo(num): print(num) if num > 100000: return 'end' else: return foo.call(num+1) foo(1) 
  • It turned out a bike for tail recursion :) - andreymal