10/38
Part 3 of 7 · Your own stackLearn

Deeper than Python's recursion limit: keep your own stack

Every recursive walk above has a limit, and a deep tree finds it.

A chain, run from a scriptsize with sum(...)size with a for loop
frames per level2: the call and its generator1
frames at the deepest call1 + 2 × 499 = 9991 + 999 = 1,000
regions that fit499, and 500 don't999, and 1,000 don't

Each call that hasn't returned yet holds a frame on the call stack. Python's recursion limit caps how many frames can be in use at once. The docs call it the maximum depth of the Python interpreter stack. The default is 1,000, and going past it raises RecursionError.

A chain is the deep case: its height is n−1n - 1. Run from a script, size as written above raised RecursionError: maximum recursion depth exceeded at 500 regions. With a plain for loop in place of sum(...), it reached 999.

The generator expression inside sum runs in a frame of its own, and the script's top level, <module>, takes one more. In a notebook or a test runner, more frames are in use before your code starts, so the numbers can come out lower.