Python, the stack, and the heap

Chris Angelico rosuav at
Mon Dec 17 14:42:28 EST 2018

On Tue, Dec 18, 2018 at 6:36 AM Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
> I've been writing Python for good long while now without thinking too
> hard about this, but I just had a realization this weekend.
> Back when the earth's crust was still cooling and we all rode dinosaurs
> to our jobs, local variables got allocated onto the stack, and dynamic
> memory from malloc or DIM explicitly allocated variables on the heap.
> Python's objects all have a lifespan dictated by the continued existence
> of references to them and thus can transcend the lifetime of the current
> function in ways not known at translation time.  So am I right in
> thinking that all Python objects are out on the heap?  And that the
> references themselves may or may not wind up on the stack depending on
> what flavor you're running?
> Answers to these questions have very little bearing on how I actually
> write Python, mind, but now I'm curious.

Correct, all Python objects exist on the heap (ignoring the fact that
the language doesn't actually define them in those terms). References
that are from a function's locals could be seen as being on the stack;
in CPython, you can mess around with sys._getframe() to explore the
stack, and each level of the stack has an f_locals attribute that has
all the local name references at that level. But not *all* references
are on the stack; some are attached to modules (those we tend to call
"globals"), or other objects (eg a list's elements), or might even be
core references (eg there's a few references to None, MemoryError, and
such, deep inside the interpreter). But basically all Python objects
are on the heap.

(Except when they're not, but even then, you can pretend that they
are. Optimization is black magic.)


More information about the Python-list mailing list