1.2.39Introduction to Programming (Python)

Recursion depth limit — stack overflow

1,765 words8 min readdifficulty · medium1 backlinks

WHAT is happening


WHY does a limit even exist


HOW it works step by step

Consider an infinite recursion (the classic bug):

def boom(n):
    return boom(n + 1)   # no base case → never stops
boom(0)
Figure — Recursion depth limit — stack overflow

Inspecting and changing the limit


Worked examples


The 80/20 takeaway


Flashcards

What data structure stores active function calls?
The call stack (LIFO), holding one stack frame per active call.
What is a stack frame made of?
The call's local variables, arguments, and return address (where to resume in the caller).
Define recursion depth.
The number of stack frames active (paused) at the same time during recursion.
What is the default recursion limit in CPython?
About 1000 total frames.
What error does Python raise on too-deep recursion?
RecursionError: maximum recursion depth exceeded.
Why does Python use a soft limit instead of crashing?
To raise a catchable RecursionError before the OS hits a hard, uncatchable stack overflow (segfault).
How do you read and change the limit?
sys.getrecursionlimit() and sys.setrecursionlimit(N).
Why is raising setrecursionlimit dangerous?
Too high a value can let recursion exhaust real stack memory, causing an uncatchable segfault.
Two robust fixes for hitting the limit?
Ensure a correct base case that's actually approached, or rewrite the algorithm iteratively.
Why does the limit not allow exactly 1000 of YOUR calls?
It counts all frames including pre-existing ones, so available depth ≈ 1000 − (already-stacked frames).

Recall Feynman: explain to a 12-year-old

Imagine you're stacking dinner plates. Every time a function calls itself, you put one more plate on the pile — that plate remembers what the function was doing. When the deepest function finishes, you take a plate off. But if a function keeps calling itself and never finishes, you keep stacking plates forever. Eventually the pile is too tall and would crash to the floor. Python is smart: at about 1000 plates it shouts "STOP! RecursionError!" instead of letting the whole thing topple. To really fix it, give the function a clear finish line (base case) it actually reaches — or use a simple loop that uses just one plate over and over.

Connections

Concept Map

pushes frame onto

each frame holds

increases

causes unbounded

frames never popped

exceeds

Python raises

fixed small memory 1-8 MB

prevented by

without limit would be

inspect and change via

counts all frames not per function

Function calls itself

Call stack LIFO

Locals args return address

Recursion depth

Base case missing or wrong

Depth climbs each call

Max recursion depth default 1000

RecursionError catchable

Stack overflow risk

OS-level segfault

sys.getrecursionlimit setrecursionlimit

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, jab bhi ek function khud ko call karta hai (recursion), Python ko yaad rakhna padta hai ki "main kahan tha, kahan wapas aana hai". Yeh yaad-rakhne wala note ek stack frame hota hai, aur saare frames ek call stack pe plate ki tarah ek ke upar ek rakhe jaate hain. Har naya call = ek nayi plate upar. Agar function rukta hi nahi (base case galat ya missing hai), to plates badhti hi jaati hain.

Stack ki memory bahut chhoti aur fixed hoti hai, isliye CPython ek default limit ~1000 rakhta hai. Jaise hi depth 1000 cross karti hai, Python ek RecursionError throw kar deta hai — yeh ek soft limit hai taaki program seedha OS-level segfault se na mare. Matlab tum is error ko try/except se pakad bhi sakte ho, jo segfault me possible nahi tha.

Sabse common galti: log sochte hain "limit chhoti hai, chalo sys.setrecursionlimit ko 10 lakh kar dete hain." Yeh khatarnaak hai — agar tum real stack memory khatam kar do to uncatchable crash aa jaayega. Asli fix do hi hain: ya to base case sahi karo jo actually reach ho (har call base ke kareeb jaaye, jaise f(n-1)), ya phir algorithm ko loop (iteration) me likho jo sirf ek frame use karta hai chahe n 20 lakh ho.

Yaad rakhne ke liye: "No Base → Frames Race → Stack's out of Space." Bas itna samajh lo to recursion bug kabhi nahi haraega.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections