All Courses

How python garbage collector works?

By Albert, 2 years ago
  • Bookmark

how to automatically deletes unwanted objects and free memory space in python?

Garbage collector
1 Answer

Python automatically deletes unwanted objects (built-in types or class instances) to free the memory space. The process by which Python automatically frees and reclaims blocks of memory that no longer are in use is called Garbage Collection.

Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a container (list, tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. When an object's reference count reaches zero, Python collects it automatically.

x = 10     # Create object <10>
y = x      # Increase ref. count of <10>
z = [y]    # Increase ref. count of <10>
del x      # Decrease ref. count of <10>
y = 100    # Decrease ref. count of <10>
z[0] = -1  # Decrease ref. count of <10>

You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.


This __del__() destructor prints the class name of an instance that is about to be destroyed −

class Point:
    def __init__( self, x=0, y=0):
      self.x = x
      self.y = y
    def __del__(self):
      class_name = self.__class__.__name__    
      print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1

print (id(pt1), id(pt2), id(pt3)) # prints the ids of the objects

del pt1
del pt2
del pt3

81223072 81223072 81223072
Point destroyed

Your Answer


How To Land a Job in Data Science?

Feb 9th (7:00 PM) 184 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More