Question presented to candidate: "In languages like C or Java people talk about values on the stack and objects on the heap. How does that map to Python? What lives on the call stack, what lives on the heap, and what consequences does that have for recursion, closures and memory?"
What a strong answer should cover:
- The call stack is the stack of frames, one per active function call; a frame holds the local variable slots (references), a small evaluation stack, and the position in the bytecode, and is linked to its caller via
f_back. - Every Python object, including ints and strings, lives on the heap; locals in a frame are only references to heap objects. There is no "value type on the stack" in Python.
- When a call returns its frame is discarded, but objects it created survive if anything still references them (a return value, a closure cell, a global).
- The stack is bounded:
sys.getrecursionlimit()(1000 by default) raisesRecursionError; deep recursion can be converted to a loop with an explicit list as the stack, which lives on the heap. - CPython details: since 3.11 frames are cheap internal structures and frame objects are created lazily; generators keep their frame alive between
next()calls; tracebacks keep frames and all their locals alive.
Code / implementation expected: Optional β walking sys._getframe() up the stack, or showing a recursive function hit RecursionError while an explicit-stack version succeeds.