Saturday 3 June 2017

Python variables and Memory Management

Python variables work more like tags unlike the boxes. When you do an assignment in Python, it tags the value with the variable name.
a = 1
and if you change the value of the varaible, it just changes the tag to the new value in memory.
a = 2
a = 2 1
Assigning one variable to another makes a new tag bound to the same value as show below.
b = a
b = a

a value will have only one copy in memory and all the variables having this value will refer to this memory location. 
>>> a = 10
>>> b = 10
>>> c = 10
>>> id(a), id(b), id(c)
(140621897573616, 140621897573616, 140621897573616)
>>> a += 1
>>> id(a)
140621897573592
id() will return an objects memory address (object's identity).
 
Python manages memory using reference counting semantics. Once an object is not referenced anymore, its memory is deallocated. But as long as there is a reference, the object will not be deallocated.
Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.
 
  del keyword merely decrements the objects reference count and de-scopes the variable on its application. But it doesn't necessarily invoke the object's __del__() method. __del__ method will be called only when the garbage collection kicks in. And this would happens automatically when the reference count of an object becomes zero.
del: Decrements reference count
__del__(): Object destructor. Called when an object is garbage collected.



 

No comments:

Post a Comment