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 weakref class elephant(): pass #SLIDE 1 #Initializing an int and a string my_int1 = 10 my_object = elephant() #SLIDE 2 #Displaying id before update print("ID before update:", hex(id(my_int1))) #Updating my_int1 value my_int1 *= 2 #Displaying id after update print("ID after update:", hex(id(my_int1))) #Creating a weak reference to my_string my_object2 = weakref.ref(my_object) #my_string and my_string2 points to same memory location print("my_object location:", hex(id(my_object))) print("my_object2 weak reference:", my_object2) #SLIDE 3 #Removing my_string reference my_object = None #SLIDE 4 #my_string2 points to dead space print("my_object2 weak reference:", my_object2)
my_objectis a strong reference to the object
my_int1changes 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_objectis no longer pointing to the object
elephant, references to this object are equal to .
View all Courses