What is Python's default recursion limit and how can you increase it safely? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

What is Python's default recursion limit and how can you increase it safely?

message-square
0

Python’s default recursion limit is 1000 stack frames (checkable via sys.getrecursionlimit()), which prevents infinite recursion from exhausting the C call stack and crashing the interpreter with a segmentation fault—you can raise it temporarily via sys.setrecursionlimit(new_limit) (ideally paired with threading.stack_size(...) for worker threads or wrapped in a contextlib.contextmanager), though converting deep recursion into an explicit iterative stack (while stack:) is always safer for unbounded inputs.

Basic Example

import sys
from contextlib import contextmanager

# 1. Inspect the default recursion limit:
print(sys.getrecursionlimit())
# Output: 1000

# 2. Recommended: Temporarily raise the limit inside a scoped context manager
@contextmanager
def temporary_recursion_limit(limit: int):
    old_limit = sys.getrecursionlimit()
    sys.setrecursionlimit(limit)
    try:
        yield
    finally:
        sys.setrecursionlimit(old_limit)

def countdown(n: int) -> int:
    if n <= 0:
        return 0
    return 1 + countdown(n - 1)

with temporary_recursion_limit(5000):
    print(countdown(3000))
# Output: 3000

print(sys.getrecursionlimit())
# Output: 1000 (safely restored)

Key Details & Edge Cases

  • Why sys.setrecursionlimit() can cause a hard C Segmentation fault (instead of RecursionError):
    • Python’s recursion limit does not allocate extra memory—it merely sets the threshold at which Python raises a catchable RecursionError: maximum recursion depth exceeded. Each recursive Python call still consumes real C stack memory (typically ~1 KB–4 KB per frame depending on OS and C extensions). Setting sys.setrecursionlimit(10_000_000) bypasses Python’s safety guard and lets deep recursion overflow the OS thread stack, crashing the entire process with a Segmentation fault (exit code 139) or Windows 0xC00000FD stack overflow.
  • Worker threads have much smaller default C stacks on Linux/macOS (threading.stack_size()):
    • While the main thread on Linux/macOS usually gets an 8 MB C stack (~3,000–8,000 Python frames), secondary threading.Thread workers on some platforms default to smaller stack sizes (e.g., 512 KB–1 MB on macOS or Alpine/musl Linux). If you run deep recursion inside a thread, configure threading.stack_size(64 * 1024 * 1024) (64 MB) before creating and starting the thread:
      import sys, threading
      
      sys.setrecursionlimit(20_000)
      threading.stack_size(64 * 1024 * 1024)  # Must be called before Thread() creation
      t = threading.Thread(target=countdown, args=(15_000,))
      t.start()
      t.join()
      
  • Guard against lowering sys.setrecursionlimit() below the current call stack depth:
    • Calling sys.setrecursionlimit(n) where n is less than or equal to the number of active frames currently on the stack immediately raises RecursionError inside setrecursionlimit() itself.
  • Why Python does not optimize Tail Recursion (TCO):
    • CPython intentionally omits Tail Call Optimization so stack tracebacks preserve every function frame for accurate debugging. Even tail-recursive functions hit the 1000 limit unless rewritten iteratively.
  • Prefer an explicit iterative list stack for trees, graphs, and ASTs of arbitrary depth:
    • Converting recursive DFS/tree traversal to a heap-allocated Python list (stack = [root]; while stack: node = stack.pop()) supports millions of levels with zero C stack risk and faster execution than recursive function calls.

Comparison of Deep-Recursion Handling Approaches in Python

Approach Max Practical Depth Can Cause Hard Segfault? Modifies Global Interpreter State? Best Used When
Iterative loop with explicit list stack (Recommended for unbounded data) Millions (limited only by system RAM) No No Parsing deeply nested JSON/XML/ASTs, graph DFS, or processing arbitrary user-supplied input sizes.
Scoped sys.setrecursionlimit(N) context manager (Recommended when recursion is required) ~3,000–20,000 (bounded by OS C stack size) Yes (if N exceeds OS thread stack memory) Temporarily (restored in finally:) Algorithms with known, moderate bounded depth (e.g., 2,000–10,000 levels) or third-party recursive libraries.
threading.stack_size(bytes) + sys.setrecursionlimit(N) ~20,000–100,000+ (up to configured stack size) No (if stack_size is sized well above N * frame_size) Yes (affects newly spawned threads) Running deep recursive algorithms inside worker threads on platforms with small default thread stacks.
Global sys.setrecursionlimit(10**7) (Avoid) Unpredictable Yes (crashes Python abruptly on stack overflow) Yes (permanently disables safety net) Never use arbitrarily huge limits in production code.