2

I just watched this informative video on memory management in Python. In it, the presenter used the following code example (at about the 4:15 mark):

x = 300
y = 300

In this case, we have two names (x and y), each pointing at a value of 300. How did Python, when executing the y = 300 line, know that it didn't need to allocate memory but rather increase the reference count, since memory for that value had already been allocated (through x)? Is the interpreter comparing values on each instantiation? If so, how does it keep track of the values it already knows about (I would assume it would do so using a dict)?

Suppose I introduced a new variable:

z = 100 + 200

Would z end up simply increasing the reference count to 300 once more?

When I try the following in my REPL (Python 3.6, Windows 7 x64), I get differing memory locations, which further confuses me (though, to be fair, she says not to try this in a REPL):

>>> x = 300
>>> y = 300
>>> print(id(x))
31191600
>>> print(id(y))
31191648
Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • If I execute the example code on my machine and I call `id(x)` and `id(y)` to inspect the memory addresses of these two variables, I get two different results. If they are references to the same underlying C object, they should have the same memory address, should they not? – Peter Wang Oct 14 '18 at 01:26
  • 2
    The video is misleading; Python makes no promises about whether any two uses of `300` use the same object. Depending on how you execute the code, it might end up making two objects. – user2357112 Oct 14 '18 at 01:28
  • I also get that result, @PeterWang (just edited my question to include that info). In the video, the presenter gets the same value. Perhaps she's using a different Python implementation than I am? – Jonah Bishop Oct 14 '18 at 01:29
  • 1
    This behavior is relying on certain, implementation-specific optimizations that are not generalizable to objects in general. Suffice it to say, during compilation, the Python runtime can recognize certain immutable literals and only creates one object . – juanpa.arrivillaga Oct 14 '18 at 02:21

0 Answers0