Python is an interpreter based language that dynamically allocates memory using its Memory Manager. Although it takes away the liberty of managing the memory from the developer, it hands out some tools to make the code more robust and understandable.
Since there is no option for manual memory management, Python uses a built-in Garbage Collector that continuously looks for un-referenced objects and deletes them from memory. This ensures good optimization of memory at the cost of the speed of code execution.
Heap space in Python primarily maintains all objects and data structures, whereas its counterpart, stack space, contains all the references to the objects in heap space.
When an object is updated, the new value is written at a new location and the variable is referenced to the new address. As soon as references to an object reach , the Garbage Collector wipes it from the heap. This is different from other languages like C++, where the value is updated at the same location.
Below is a small code to demonstrate how the heap functions.
import weakrefclass elephant():pass#SLIDE 1#Initializing an int and a stringmy_int1 = 10my_object = elephant()#SLIDE 2#Displaying id before updateprint("ID before update:", hex(id(my_int1)))#Updating my_int1 valuemy_int1 *= 2#Displaying id after updateprint("ID after update:", hex(id(my_int1)))#Creating a weak reference to my_stringmy_object2 = weakref.ref(my_object)#my_string and my_string2 points to same memory locationprint("my_object location:", hex(id(my_object)))print("my_object2 weak reference:", my_object2)#SLIDE 3#Removing my_string referencemy_object = None#SLIDE 4#my_string2 points to dead spaceprint("my_object2 weak reference:", my_object2)
my_object
is a strong reference to the object elephant
.my_int1
changes after it is updated.my_object
. This weak reference does not increase the number of references to the object, it just shows its location. Therefore, we need at least one strong reference to keep the object alive, otherwise, the Garbage Collector destroys it to optimize memory.my_object
is no longer pointing to the object elephant
, references to this object are equal to .