Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean that python is stack based?

Tags:

python

I have read how CPython is stack based. What does it mean? When I use the dis module, I see operations like LOAD_FAST etc, where the values are placed on a stack. But I have read that all values in python are objects and hence go in the heap. I guess I am confusing two different things here. I have also read that there is something called stackless python. Can someone clarify this?

like image 306
codingsplash Avatar asked Sep 05 '25 03:09

codingsplash


1 Answers

The most popular python interpreter, CPython, can be viewed as a stack based virtual machine. It means that python code is compiled for an imaginary (virtual) computer with a stack architecture.

The other aspect is how this virtual machine is implemented. It's clearly not a piece of hardware (and attempts of processor manufacturers to add support for some virtual machines, for example JVM, are usually not successful). So, this stack machine is emulated by a program written in C and it is a part of the CPython interpreter.

Regarding how do stack and heap live together, it should be clear now - the virtual machine and the stack, both are placed in the heap memory. Using LOAD_FAST places an object on the top of the stack from the virtual machine point of view, and the very same instruction places object in the heap from an OS point of view.

like image 94
u354356007 Avatar answered Sep 07 '25 17:09

u354356007