RecursionError: maximum recursion depth exceeded
What it means
A function kept calling itself until Python stopped it after a set number of nested calls. Almost always the function has no base case (a condition that returns without calling itself again), or its base case is never reached. The traceback shows the same line repeated many times.
1. No base case
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> File "<exec>", line 2, in factorial File "<exec>", line 2, in factorial File "<exec>", line 2, in factorial [Previous line repeated 992 more times] RecursionError: maximum recursion depth exceeded
The fix
120
The base case returns a value without another call, so the chain of calls ends and the results multiply back up to 120.
2. A base case that is never reached
This raises the error
Traceback (most recent call last): File "<exec>", line 6, in <module> File "<exec>", line 4, in count_down File "<exec>", line 4, in count_down File "<exec>", line 4, in count_down [Previous line repeated 992 more times] RecursionError: maximum recursion depth exceeded
The fix
Liftoff!
Stepping by 2 from 5 gives 3, 1, -1 and so on, skipping 0 forever. A condition like n <= 0 catches every way past the end.
3. A property that reads itself
This raises the error
Traceback (most recent call last): File "<exec>", line 10, in <module> File "<exec>", line 7, in name File "<exec>", line 7, in name File "<exec>", line 7, in name [Previous line repeated 992 more times] RecursionError: maximum recursion depth exceeded
The fix
Ana
Inside the property, self.name runs the same property again, forever. Reading the stored attribute self._name ends the loop.
When you see this error, check
- Find the line repeated in the traceback: that is the call that never stops.
- Make sure every recursive function has a base case that returns without calling itself.
- Check that each call moves closer to the base case, and prefer
<=to==when steps can jump past it. - For recursion that is correct but very deep, rewrite it with a loop instead of raising
sys.setrecursionlimit().
Related errors
All Python errors · How to read a traceback · Step through your code