1

(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
  • 1
    Note that python has several kinds of scope (roughly global, class, closure and function) all of which work differently. x=3 can mean wildly different things in terms of implementation depending on the scope, including whether the name x even is an actual thing that needs allocating. Commented Aug 2, 2020 at 9:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I believe that Python functions use a stack that is part of the heap.
@NSR: yes... the "stack frame" is in C heap and contains the locals and received parameters. However nested function calls end up in nested calls in C. I don't really understand the reason of this choice, but basically this is what imposes a recursion limit for python functions (much smaller than the size of the heap).
So does Python use a stack for allocating memory?
Is "C heap" and "Python heap" different?
@NSR: python does not use C stack to implement Python call stack for the parameters. Python memory model is different from C because it supports read/write closures so local variables cannot be allocated on a stack. That said however for some reason that I don't understand fully C stack is being used for nested function calls, and this means that unlimited recursion in CPython ends up in C stack overflow much before heap exhaustion. This is not the only possibile implementation, but last time I checked was what was used by CPython.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.