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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

12 lines
Python 3.9+
import 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

stdout
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

  1. Use `sys.setrecursionlimit()` to change the limit before running recursion.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.