Garbage Collection

Garbage Collection

Python uses Garbage Collection to free up memory that was given to the program after it has completed execution, and this also includes memory that was once given to a program at a certain time but is no longer in use by the program.

Garbage collection helps us in memory management and also helps us to completely utilize our memory so that it is not wasted, and the memory that is freed can now be used by other programs.

Garbage collection occurs automatically in Python, and it happens when no reference to an object or variable exists which indicates that the program has no longer a need for it and its memory allocation can be freed.

Consider an example of this:

class Collector:
    def __init__(self, number):
        self.object_number = number
        print(f"Created object_{self.object_number}")

    def __del__(self):
        print(f"Deleted object_{self.object_number}")

object_1 = Collector(1)

print("\nCreating a reference to object_1")
object_1_2 = object_1

object_2 = Collector(2)

print("\nSetting object_1 to None")
object_1 = None
print("Deletes only when all references are deleted as well")

print("\nSetting object_2 to None")
object_2 = None

# Setting reference to object_1 to None
print("\nSetting object_1_2 to None")
object_1_2 = None

The output would be:

First, we created a class called “Collector” and its constructor takes a number to represent the object number and displays a statement once the object is created. Then we created another object called “object_1_2” which references “object_1”.

When we set an object to ‘None’, the object is destroyed unless there exists a reference to the same object, say using a variable. Only when the referencing variables are also set to None, only then will the original object be destroyed.

So, we first created “object_1” then the reference to it, called “object_1_2”  and the last thing we created was an object called “object_2”. Then we initially set “object_1” to None, and since the object has been destroyed the destructor should have been called, but we notice that it does not. When we set “object_2” to None, the object was destroyed and we see that the destructor has been called. This is because Python sees that no other references to “object_2” exist.

Now when we set “object_1_2” to None, we see that the destructor of “object_1” was called since all references to that object were destroyed.

There might be times when we need to manually clear our unused memory allocations. We can achieve this using the “gc” module. Specifically, we use the collect() function from this module to forcibly achieve Garbage Collection. Consider the following situation:

import gc

# Create 10 empty dictionaries
for x in range(10):
    # This dictionary points to itself again and again
    empty_dict = { }
    empty_dict[x] = empty_dict

objects_left = gc.collect()

print("Collected", objects_left, "objects")

When we run this program, we get:

The collect() function collects all of the unused objects, or in other words objects that have 0 references. These objects are unused as they are unreachable and thus Python cannot implicitly get rid of them. In such cases we need to use the collect() function to get rid of them; the collect() function returns the number of unused objects that were collected by the garbage collector.


What have we learned?

  • What is the Garbage Collector?
  • What are some of the advantages of Garbage Collection?
  • What are the two approaches to Garbage Collection?
  • Which module can we use for Garbage Collection?
  • What does the collect() function return?
Notify of
Inline Feedbacks
View all comments