(CPython implementation)
In x = 3, I know that the memory for the int object containing the primitive value 3 is allocated on the heap. Is x (as a reference to the int object) allocated on the stack or on the heap?
1 Answer
Objects in CPython implementation are allocated on the heap and the same happens for "stack frames". The "stack frame" size is precomputed at compile time.
However for reasons that are not 100% clear to me there is a C stack use for nested function calls (not for arguments or locals, however). This still means that inifinite recursion on CPython will crash because of C stack exhaustion much before than running out of memory. It could have been possible to implement the VM to use a fixed amount of C stack no matter how deep was the call nesting in Python code, but this is not the case.
Note also that small integers (e.g. 3) are however shared, i.e. a new integer object is not always allocated. Being integers immutable this is hard to notice except when using id, but is an important optimization for speed reasons.
x=3can mean wildly different things in terms of implementation depending on the scope, including whether the namexeven is an actual thing that needs allocating.