RecursionError (Python)
In short: A function calls itself too often without stopping; Python aborts at about 1000 levels.
In more detail: Message: RecursionError: maximum recursion depth exceeded. Each function call occupies space on the call stack. Python limits the depth (default about 1000) to prevent a crash. It is the Python counterpart to Java’s StackOverflowError.
In Depth
Possible causes
- Missing or wrong base case: the recursion has no end.
- The step does not lead towards the base case (for example
ndoes not get smaller). - Mutual recursion between two functions.
- Very deep but legitimate recursion (long lists, trees, deep graphs).
- A method unintentionally calls itself through
__getattr__/property.
Example
def factorial(n):
return n * factorial(n - 1) # base case missing!
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)Solutions
- Check the base case: is it reached every time?
- Work with a loop and own stack instead of recursion (iterative).
- Tail recursion is not optimised by Python; rebuild manually.
- For legitimate deep recursion set
sys.setrecursionlimit(10000)(carefully, crash risk) or switch to iteration. - Memoisation (
functools.lru_cache) avoids repeated calls but does not solve a depth problem. - Print the arguments with
printand check how they change.
See also: StackOverflowError, Recursion, Stack and heap