Reputation: 27697
I'm running a recursive loop to achieve the maximum optimization for something and am reaching a point where the code hits a RuntimeError: maximum recursion depth exceeded while calling a Python objec
t. This is expected, but I want to stop the code right at the point before it hits that error, so I can view my data at that point.
Is it possible to have a while loops saying something similar to that? Something like "Hey, run this loop until you reach maximum recursion depth. Once reached, stop and return."
Thanks for the help!
Upvotes: 4
Views: 1817
Reputation: 13088
You can do the following
def recurse():
try:
recurse()
except RuntimeError as e:
if e.message == 'maximum recursion depth exceeded while calling a Python object':
# don't recurse any longer
else:
# something else went wrong
http://docs.python.org/tutorial/errors.html
NOTE: it might be worth while to find out the error number of the max recursion depth error and check for that instead of the error string.
Upvotes: 6
Reputation: 113955
Store sys.maxrecursionlimit()
as a variable (say maxrec
) in a more global scope. Each time you recurse, deduct 1
from maxrec
. Check before the recursion, though to make sure that maxrec
is not 0
. If maxrec
hits 0
, you'll know that you've hit the recursion limit and you can escape.
def myFunc(params):
# do stuff
if maxrec <= 0:
return # return whatever you need to
if maxrec > 0:
maxrec -= 1
myFunc(params)
maxrec = sys.getrecursionlimit()
myFunc(params)
Hope this helps
Upvotes: 1
Reputation: 731
Perhaps, have the recursive call in a try/except RuntimeError block? When the except is called return the value.
EDIT: Yes this is possible, like so:
def recursion(i):
try:
return recursion(i+1)
except RuntimeError:
return i
a=0
print recursion(a)
Upvotes: 2