Learning Memory Allocation in Python

Viewed 55

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?

1 Answers

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 = {}).

Related