How to Detect the Recursion Limit in Python with sys.getrecursionlimit
This Python code recursively calls itself, printing the current recursion depth and the recursion limit from sys.getrecursionlimit, and catches the RecursionError when the limit is hit.
Python code
12 linesimport sys
def recurse(depth=0):
print(f"Depth: {depth}, Recursion limit: {sys.getrecursionlimit()}")
return recurse(depth + 1)
if __name__ == "__main__":
try:
recurse()
except RecursionError:
print("Recursion limit reached!")
print(f"Final recursion limit: {sys.getrecursionlimit()}")
Output
Depth: 0, Recursion limit: 1000
Depth: 1, Recursion limit: 1000
...
Depth: 999, Recursion limit: 1000
Recursion limit reached!
Final recursion limit: 1000
How it works
The sys.getrecursionlimit() function returns the current recursion limit (default is 1000). Each recursive call increments the depth until the limit is exceeded, triggering a RecursionError. The try/except block catches that error and prints a message along with the final limit. This pattern is useful for debugging recursion depth issues and understanding stack limitations.
Common mistakes
- Forgetting that the actual maximum depth may be lower due to the stack frame size of the recursive function.
- Assuming the recursion limit is always 1000; it can be changed with `sys.setrecursionlimit()`.
- Not catching `RecursionError` outside the recursive function, causing an unhandled exception.
Variations
- Use `sys.setrecursionlimit()` to change the limit before running recursion.
- Instead of printing each depth, use a counter to track the maximum depth reached before the error.
Real-world use cases
- Debugging why a recursive algorithm crashes with a RecursionError in a production script.
- Estimating the safe depth for recursive data processing like traversing deeply nested JSON trees.
- Verifying the effective recursion limit before writing deep recursive functions, such as for directory walking.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.