Skip to content Skip to sidebar Skip to footer

Python Different Memory Management Behaviours When Run In Python Shell And *.py File

Example 1: ➜ /tmp cat t.py a = 250000000000 b = 250000000000 print id(a), id(b), id(a) == id(b) ➜ /tmp python t.py 140450848587992 140450848587992 True #(Why is True?)

Solution 1:

If I were the Python interpreter reading the .py file (as in your first example), I'd allocate memory for this number only once and then make a and b point to this location.

For example, the interpreter reads this file and sees that two variables are assigned the same value and thinks: "Do I want to waste memory by allocating two portions for the same value? No, I don't. Instead, I'd better allocate one single chunk and store this value in it". So, there's only one copy of this value and that's why these variables have identical id's.

In the second case Python has to allocate memory when you do the assignment, so there are two pieces of memory with the same data.

To sum up, in the first case the interpreter knows much more about the code (the whole code is given), so it can optimize it (and generate .pyo files) while in the second one it simply can't do any optimization.


Solution 2:

Actually the CPython runtime does indeed "interns" (cache) some immutable objects (ints up to a certain value, strings that could be legal python identifiers etc) as an optimisation. All of this behaviour is totally implementation dependant and should not in any case be relied upon, as you just noticed.


Post a Comment for "Python Different Memory Management Behaviours When Run In Python Shell And *.py File"