What is the maximum recursion depth in Python, and how to increase it?
What is the maximum recursion depth in Python, and how to increase it?
It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesnt optimize tail recursion, and unbridled recursion causes stack overflows. You can check the recursion limit with sys.getrecursionlimit
:
import sys
print(sys.getrecursionlimit())
and change the recursion limit with sys.setrecursionlimit
:
sys.setrecursionlimit(1500)
but doing so is dangerous — the standard limit is a little conservative, but Python stackframes can be quite big.
Python isnt a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.
Looks like you just need to set a higher recursion depth:
import sys
sys.setrecursionlimit(1500)
What is the maximum recursion depth in Python, and how to increase it?
Its to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows.
Try increasing the recursion limit (sys.setrecursionlimit
) or re-writing your code without recursion.
From the Python documentation:
sys.getrecursionlimit()
Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by
setrecursionlimit()
.