RecursionError
RecursionError
is a built-in exception that occurs when the maximum recursion depth is exceeded. Recursion is a programming technique where a function calls itself to solve a problem.
Without a proper base case that stops the recursive calls, recursion can lead to potentially infinite loops, consuming memory with each call. To prevent this, Python sets a limit on the recursion depth. Exceeding this limit triggers a RecursionError
.
RecursionError
Occurs When
A RecursionError
appears when a function calls itself directly or indirectly often enough to reach Python’s recursion limit.
RecursionError
Can Be Used When
Typically, you won’t raise RecursionError
yourself. When Python raises a RecursionError
, you can use it as a sign that your recursive code logic is buggy.
RecursionError
Example
An example of when the exception appears:
>>> def recurse():
... recurse()
...
>>> recurse()
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
As this recursive function doesn’t have a proper base case that ends the call cycle, it will keep calling itself until Python eventually raises a RecursionError
.
RecursionError
How to Fix It
Here’s another buggy piece of code that raises a RecursionError
:
>>> def count_down(n):
... print(n)
... return count_down(n - 1)
...
>>> count_down(5)
5
4
3
2
1
0
-1
-2
...
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
To fix it, ensure your function has a base case that terminates the recursion:
>>> def count_down(n):
... print(n)
... if n <= 0:
... return "Done"
... return count_down(n - 1)
...
>>> count_down(5)
5
4
3
2
1
0
'Done'
The highlighted lines add a base case that terminates the recursion when the value of n
goes down to zero.
By default, Python has a recursion depth limit of 1000 calls:
>>> import sys
>>> sys.getrecursionlimit()
1000
You can change this limit using the sys.setrecursionlimit()
function.
Related Resources
Tutorial
Recursion in Python: An Introduction
In this tutorial, you'll learn about recursion in Python. You'll see what recursion is, how it works in Python, and under what circumstances you should use it. You'll finish by exploring several examples of problems that can be solved both recursively and non-recursively.
For additional information on related topics, take a look at the following resources:
- Thinking Recursively in Python (Tutorial)
- Recursion in Python (Course)
- Thinking Recursively With Python (Course)