Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect a max. recursion depth exceeded exception in Python?

Tags:

python

try:
    recursive_function()
except RuntimeError e:
    # is this a max. recursion depth exceeded exception?

How do I tell when the maximum recursion depth has been reached?

like image 324
Jay Avatar asked Jun 27 '12 18:06

Jay


People also ask

How do you find the maximum recursion depth in Python?

Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.

How do you solve maximum recursion depth exceeded?

The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.

How do I fix RecursionError maximum recursion depth exceeded while calling a Python object?

A Python RecursionError exception is raised when the execution of your program exceeds the recursion limit of the Python interpreter. Two ways to address this exception are increasing the Python recursion limit or refactoring your code using iteration instead of recursion.


1 Answers

You can look inside the exception itself:

>>> def f():
...     f()
... 
>>> try:
...     f()
... except RuntimeError as re:
...     print re.args, re.message
... 
('maximum recursion depth exceeded',) maximum recursion depth exceeded

I don't think you can distinguish between this and something merely pretending to be a recursion-depth-exceeded (Runtime) exception, though. message is deprecated, so args is probably the best bet, and is Python-3 compatible.


Update: in Python 3.5, there's a specific RecursionError which you can catch instead.

like image 171
DSM Avatar answered Sep 18 '22 15:09

DSM