September 23, 2017

refcounts and python's Garbage collector

We all have heard things like python is a memory safe language, and memory manageement is done automatically in python.

Its the Garbage collector which is responsible for freeing memory when an object is no longer required by the program.

Consider this program below:

class A:
    def __del__(self):
        print "no more refrence to {}".format(self)

del is a magic method which is called when an object is destroyed.

create some refrences to the class A.

>>>a = A()
>>>b = a
>>>c = a

the above can be represented by something like this:

 a  │────────────┐
┌────┐    ┌───────────────┐
 b  │───▶│A() refcount=3 
└────┘    └───────────────┘
 c  │────────────┘

Now assume at some point in program we modify the above objects like this:

>>>a = 1
>>>b = 1
>>>c = 1
no refrence to <__main__.A instance at 0x7fd038735248

now since there is no refrence to class A , the object A() is destroyed and hence the output above.

above situation can be represented as :

┌────┐    ┌────┐
 a  │─┬─▶│1   
└────┘   └────┘
┌────┐   ┌───────────────┐
 b  │─┤  A() refcount=0 
└────┘   └───────────────┘
 c  │─┘