Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python possible to run while loop until RuntimeError: maximum recursion depth exceeded while calling a Python object

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 object. 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!

like image 528
user1530318 Avatar asked Jan 16 '23 17:01

user1530318


2 Answers

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.

like image 113
Matti Lyra Avatar answered Jan 18 '23 07:01

Matti Lyra


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)
like image 35
Aaron S Avatar answered Jan 18 '23 06:01

Aaron S