Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Functions & functional toolsMiddleOccasionalTroubleshooting

Why can deep recursion crash a Python program, and does Python optimize tail-recursive calls?

Answer

CPython enforces a default recursion limit, retrievable with `sys.getrecursionlimit()` (commonly 1000), and exceeding it raises a `RecursionError` as a guard rail. Since CPython 3.11, most Python-to-Python calls no longer consume a real C stack frame the way they used to — the interpreter inlines many such calls into its own frame-handling — but the recursion-depth guard still applies, and sufficiently deep or C-stack-heavy recursion (such as recursion that also crosses into C-implemented code) can still exhaust the real OS stack in some situations, so the limit remains a genuine safety mechanism rather than a leftover artifact. Unlike some functional languages, CPython performs no tail-call optimization: a recursive call written in tail position is not converted into a loop, so a deeply recursive algorithm on unbounded input should generally be rewritten iteratively or converted to use an explicit stack rather than relying on the interpreter to flatten it.

Strong answer includes

  • default recursion limit around 1000, raises RecursionError as a guard rail
  • since 3.11 most Python-to-Python calls no longer consume a real C stack frame, but the depth guard and some C-stack risk remain
  • CPython does not perform tail-call optimization

Practical example

A naive

Python example
def sum_to(n): return n if n == 0 else n + sum_to(n - 1)

raises RecursionError around

Python example
sum_to(2000)

, but an iterative loop or

Python example
sum(range(n + 1))

handles arbitrarily large `n` with flat memory use.

#recursion#performance

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules