BOMBOLOM.COM

(python) Maximum Recursion Depth Exceeded

Posted by José Lopes

If you get the following error message when you execute a function with Python:

RuntimeError: maximum recursion depth exceeded

It means that the recursion limit of your platform was exceeded, but this can be easily fixed.

The recursion limit exists to avoid an infinite recursion that would cause an overflow and the crash of Python.

To check the current value of this limit we can do:

import sys
print sys.getrecursionlimit()

This will print to the screen a number that represents the current recursion limit.
This number can be changed with:

sys.setrecursionlimit(n)

Where n should be an integer defining the new limit.

When I said that this problem can be easily fixed I did mean it but there's more to it.
Usually when you define a new limit the problem is fixed but, since this limit depends on the platform resources you are using, it may not be sufficient and compel to a code revision or optimization.

The recursion limit can always be changed if the program needs a high degree of recursion and if the platform supports that higher value.

Then you would ask what is the maximum value that my platform supports?

Since this value doesn't appear written anywhere we must create a test baterie to calculate it. If search the web for such thing you will find a program that test your system capacity at svn.python.org.

Nevertheless, in my opinion, using such program is a little excessive since most of the time you don't need to know the maximum limit but the necessary limit for your application, and for that id even simpler.

Lets recall the Fibonacci function, created in the Create Memoizer post, and calculate the 1000 first number of the series:

fibonacci = memo(fibonacci)
fibonacci(1000)

You probably get the RuntimeError: maximum recursion depth exceeded error.
To calculate the recursion limit value necessary to our case we can do:

fibonacci = memo(fibonacci)
n = 2000
while 1:
  sys.setrecursionlimit(n)
  try:
    fibonacci(1000)
  except RuntimeError:
    pass
  else:
    break
  n += 500
  print n

We'll get a result like:

2500
3000
3500

The value 3500 will be enough to assure that the function will work if we pass 1000 as argument.

I believe that we always have an idea of the data range for our applications, which affects our code design and solutions, so I don't find irrelevant to get the limit for a particular case instead of the system maximum limits.
This always depends of the situation and that's why I mentioned both approaches.

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box