Every C (compiled language) program has code/data/stack/extra/heap segments loaded in memory before execution. Does python interpreter create any memory layout for every python program before start interpreting the python program? If yes, How do i visualise that memory layout?
It has a kind of layout, but here the heap is the most important part, as every object is put to the heap. The code segment is merely the interpreter, the data segment is as well internal state of the interpreter, and the stack as well.
What is relevant for the Python program is only the heap. But the layout itself is like any other program.
Is const
a name of 32/64 bit memory area storing the value 2
with type assigned as integer?
It is a name in the current working space, (here: in the module's namespace), which is essentially a dict which makes assignments between strings and arbitrary objects. In this case, it makes the string const
refer to an integer object which holds the value 2
.
(This object can be created newly or re-used depending on the circumstances; this makes no difference, as it is immutable.)
add()
/sub()
/other functions are shown in Objects column as per the diagram, So, How do i perceive functions being stored as Objects? How do I visualise it?
As written in my comments to Ignacio's answer:
In the case of functions, you have an object which has certain fields, which contain e. g. the code in terms of bytecode, the number of parameters it has, etc. And it even has methods itself, for example __get__()
which is called internally for binding a method to an object, or __call__()
for the real function call, besides __format__()
, __repr__()
etc.
An integer object has, somewhere deep inside, a place for storing the actual value. In the case of a long()
in Py2, or any int()
in Py3, it stores the data to hold the value (e. g. 2
) and as well the length needed for it. Besides, it has a number of methods. Have a look at the output of dir(2)
to see it having a bunch of methods as well, such as for formatting, for arithmetics, etc.
As per the diagram, Is op
a function pointer pointing to function sub()
?
Kind of, yes.
There is a function object, which internally knows that its original name was sub
. But this knowledge is only for displaying purposes.
In your case, it is referred from two names, op
and sub
. So referring to either of them has the same result.
Note that there are no "function pointers" per se, there are just references, or names, which refer to an object of any type. The type of an object is fixed, but not the "type of a reference" (as there is no such thing).