2

I am trying to learn how referencing in Python works

val = 10
print(id(val))  # ID: 1234

val2 = 10
print(id(val2)) # ID: 1234

I am thinking that by removing all references to the number it would deallocate memory and when it is reinitialized, a new reference would be created.

val = None
va2 = None

val = 10
val2 = 10
print(id(val))  # ID: 1234
print(id(val2)) # ID: 1234

However, when I tried removing all references to object 10 and initialize the object again, it points to the same reference. Am I getting some concepts wrong regarding memory allocation in Python?

Edwin
  • 461
  • 1
  • 5
  • 14
  • 1
    See https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter – Thierry Lathuille Apr 01 '20 at 07:56
  • 1
    Note that memory allocation is an implementation detail. In fact, there is no guarantee that ``id`` yields a memory location – for example, [PyPy derives the ``id`` of certain static types from their value](https://doc.pypy.org/en/latest/cpython_differences.html#object-identity-of-primitive-values-is-and-id). – MisterMiyagi Apr 01 '20 at 08:16
  • See also [Why does ``id({}) == id({})`` and ``id([]) == id([])`` in CPython?](https://stackoverflow.com/questions/3877230/why-does-id-id-and-id-id-in-cpython) and [What is the id( ) function used for?](https://stackoverflow.com/questions/15667189/what-is-the-id-function-used-for). – MisterMiyagi Apr 01 '20 at 08:23

1 Answers1

2

Python integers between -5 and 256 are cached. Meaning Python reuses same objects. Note that this is an implementation detail and you should not depend on it. See docs: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong

Also note that once an object is destroyed, a new object may reuse old id. The only guarantee is that id is unique among currently alive objects. And so your test is not correct, even when dealing with non-cached objects (like val = {}).

freakish
  • 54,167
  • 9
  • 132
  • 169