Garbage Collector in Python

##python

Darsi Akhil Feb 21 2021 · 3 min read
Share this

1. In old languages like C++, the programmer is responsible for both the creation and destruction of objects. Usually, programmers taking care very much while creating an object, but neglecting the destruction of useless objects. Because of his negligence, total memory can be filled with useless objects which creates memory problems and total application will be down without memory error

2. But in python, we have some assistant which is always running in the background to destroy useless objects. Because of this assistant, the chance of failing a python program with memory problems is very less. This assistant is nothing but a garbage collector.

3. Hence the main objective of a garbage collector is to destroy useless objects.

4. If an object does not have any reference variable then that object is eligible for a garbage collector.

Garbage Collector:

1. At a certain point, there is no memory to create the new object because the programmer hasn't deleted waste or unuseful objects and this causes memory problems.

2. If a memory problem arises, due to which total application collapses

3. Responsibility is taken by the garbage collector in python which works internally

4. The objects which are not having the reference variable are eligible for the garbage collector

5. Advantage of the garbage collector is program never runs out of memory

6. Garbage collector (GC) calls destructor automatically and it calls just before the destruction of the object

7. GC is responsible to perform cleanup/resource deallocation activities

8. Python virtual machine (PVM) is responsible for calling the garbage collector

How to enable and disable garbage collector in python program:

By default, garbage collector is enabled, but we can disable based on our requirements. We must use gc module for this purpose

1. gc.isenabled()  #returns true if GC is enabled

2. gc.disable()    #to disable GC explicitly

3. gc.enable()     #to enable GC explicitly

Destructor concept: (Special method in python)

            syntax: __del__(self)

1. It will take care of the object before destruction but not responsible for the destruction of the object

2. Just before destroying an object, GC always calls the destructor method to perform cleanup activities. (Resource deallocation activities like database connections etc)

3. Once the destructor execution is completed then GC automatically destroys that object. Destructor fulfills the last wish of the object and then GC destroys the object

4. Once the program is executed completely, GC does not see the reference variable. So, all the objects are eligible for GC and will get destroyed.

5. Once the program execution ends, automatically objects will be destroyed then what is the use of destructor?... In the middle of the program, if the programmer needs to destroy the objects, he must use the destructor and highly recommended to disclose/deallocate the connections related to that particular object so that there is no effect on the rest of the program.

Two ways of making an object eligible for GC:

1. By using None

            syntax: Reference_variable = None

(a) None is the default object, and it will not be destroyed

(b) After executing the above syntax, automatically that particular object is eligible for GC, but reference variable is available for the future purpose

2. By using del

            syntax: del reference_variable

(a) After executing the above syntax, both object and corresponding reference variable will also be deleted

Program 1:

import time

class test:

    def __init__(self):        # constructor method

        print('obj initialization')

    def __del__(self):               # destructor method

        print('fulfilling last wish and performing cleanup activities')

t = test()  #object created with reference variable so not eligible for GC

# we can use this obj based on our requirement

# ......

# from this point, t is no longer required

t = None #explicitely making test object eligible for GC by giving same reference variable.

#Any name can be used in place of None but using other variable which is of useless other than None  is again a wastage of memory

# now test object is eligible for GC

# but variable t is available for future purpose

time.sleep(10)  #execution stops for 10 seconds at this line

print('end of application')

Output:

obj initialization

fulfilling last wish and performing cleanup activities

end of application

Program 2:

import time

class test:

    def __init__(self):

        print('initialization')

    def __del__(self):

        print('fulfilling last wish and perform cleanup activities')

        #any code we can write..close db connections...

t1 = test()   #only 1 object but 3 reference variable

time.sleep(5)

t2=t1

t3=t2

del t1

time.sleep(5) #execution stops for this time in console

print('obj not yet destroyed after deleting t1')

del t2

time.sleep(5)

print('obj not yet destroyed after deleting t2')

print('i am trying to delete last reference variable')

del t3

print('complete end of application')

Output:

initialization

obj not yet destroyed after deleting t1

obj not yet destroyed after deleting t2

i am trying to delete last reference variable

fulfilling last wish and perform cleanup activities

complete end of application

Program 3:

import time

class test:

    def __init__(self):

        print('obj initialization')

    def __del__(self):

        print('fulfilling last wish and performing cleanup activities')

list = [test(),test(),test()] #3 objects inside a list

del list

time.sleep(10)

print('end of application')

Output:

obj initialization

obj initialization

obj initialization

fulfilling last wish and performing cleanup activities

fulfilling last wish and performing cleanup activities

fulfilling last wish and performing cleanup activities

end of application

key points:

1. Once the program completes, all objects will become useless. Hence all objects will be destroyed automatically by PVM

2. If the object has at least one reference variable, then the object is not eligible for GC

3. The job of the destructor is not to destroy the object and it is just to perform clean-up activities.

4. If we are not having any cleanup activities then there is no need to write the destructor method

5. On every object constructor and destructor will be executed automatically

Comments
Read next