Thursday, August 25, 2011

RuntimeError: maximum recursion depth exceeded.

Fooling around with a simple recursive method. Apparently there is an default limit in Python preventing infinite recursion. You can bypass it by using following method of the sys class:

sys.setrecursionlimit(limit)

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.


Sample test:

# Simple recursive funcktion in Python
import sys

sys.setrecursionlimit(10000)

def method(arg):
if arg == 0:
print "End."
else:
arg -= 2
print arg
method (arg)

method(10000)




No comments:

Post a Comment