Nearby lessons

112 of 159

Python - Garbage Collection

📌 What You Will Learn
  • Understand what garbage collection is and why it is required
  • Know when an object becomes eligible for garbage collection
  • Use the __del__() destructor for cleanup activities
  • Understand how reference counting works
  • Check an object's reference count using sys.getrefcount()

Garbage Collection

Garbage Collection (GC) is the process of automatically destroying objects that are no longer required by the program.

Python provides a built-in Garbage Collector that automatically manages memory.

The programmer does not need to manually free memory as in some other programming languages.

Whenever an object becomes unused and no reference variables point to it, Python's Garbage Collector destroys the object and releases the occupied memory.

Why Garbage Collection is Required?

  • Automatically frees unused memory.
  • Improves application performance.
  • Prevents memory leaks.
  • Removes objects that are no longer required.
  • Allows programmers to focus on application logic instead of memory management.

When is an Object Eligible for Garbage Collection?

An object becomes eligible for Garbage Collection when its reference count becomes zero.

This means that no reference variable is pointing to the object.

Once the object becomes unreachable, Python's Garbage Collector destroys it automatically.

Reference Count Object Status
Greater than 0 Object is Active
0 Eligible for Garbage Collection

Destructor (__del__)

A Destructor is a special method that is automatically executed just before an object is destroyed.

In Python, the destructor method is represented by __del__().

The main purpose of a destructor is to perform cleanup activities before an object is removed from memory, such as:

  • Closing files.
  • Closing database connections.
  • Releasing network resources.
  • Freeing external resources.

Syntax

🐍Code Cell
1class Test:
2 
3 def __del__(self):
4 print("Destructor Executed")
Output
No output captured.

Program: Destructor Executes When Reference Count Becomes Zero

🐍Code Cell
1class Test:
2 
3 def __init__(self):
4 print("Constructor Execution")
5 
6 def __del__(self):
7 print("Destructor Execution")
8 
9 
10t1 = Test()
11 
12t2 = t1
13 
14t3 = t2
15 
16del t1
17 
18print("Deleted t1")
19 
20del t2
21 
22print("Deleted t2")
23 
24del t3
25 
26print("Deleted t3")
Output
Constructor Execution
Deleted t1
Deleted t2
Destructor Execution
Deleted t3

Explanation

Three reference variables point to the same object, so its reference count is 3.

Deleting t1 reduces the count to 2, and deleting t2 reduces it to 1. The object is still alive because t3 continues to reference it.

When t3 is deleted, the reference count becomes zero. The object becomes eligible for garbage collection and the destructor executes automatically before the object is destroyed.

Reference Counting

Reference Counting is the mechanism used by Python to keep track of how many reference variables are pointing to an object.

Whenever an object is created, Python maintains a count of all references pointing to that object. This count is called the Reference Count.

The Garbage Collector uses the reference count to determine whether an object is still in use. If the reference count becomes zero, the object becomes eligible for Garbage Collection.

How Reference Counting Works

  • Creating a new reference increases the count.
  • Deleting a reference decreases the count.
  • When the count becomes zero, Python destroys the object.

The reference count changes automatically during program execution.

Operation Reference Count Object Status
Create Object 1 Alive
Create t2 2 Alive
Create t3 3 Alive
del t1 2 Alive
del t2 1 Alive
del t3 0 Garbage Collection

How to Find the Number of References of an Object

Python provides the sys.getrefcount() function to display the current reference count of an object.

🐍Code Cell
1import sys
2 
3class Test:
4 pass
5 
6t1 = Test()
7 
8t2 = t1
9 
10t3 = t1
11 
12t4 = t1
13 
14print(sys.getrefcount(t1))
Output
5

Why is the Output 5?

Although only four user-created reference variables exist, the output is 5.

This happens because Python internally maintains one additional temporary reference while calling getrefcount().

Reference Count
t11
t21
t31
t41
Internal Python Reference1
Total5

Program: Object Destroyed Only After All References Are Removed

🐍Code Cell
1import time
2 
3class Test:
4 
5 def __init__(self):
6 print("Constructor Execution")
7 
8 def __del__(self):
9 print("Destructor Execution")
10 
11 
12t1 = Test()
13 
14t2 = t1
15 
16t3 = t1
17 
18del t1
19 
20time.sleep(5)
21 
22print("Object not yet destroyed")
23 
24del t2
25 
26time.sleep(5)
27 
28print("Still object not destroyed")
29 
30del t3
31 
32time.sleep(5)
33 
34print("End of application")
Output
Constructor Execution
Object not yet destroyed
Still object not destroyed
Destructor Execution
End of application

Explanation

Three reference variables point to the same object.

Deleting t1 and t2 does not destroy the object because t3 still references it.

Only after t3 is deleted does the reference count reach zero, the destructor executes, and the object is destroyed.

Program: Garbage Collection Using a List

🐍Code Cell
1import time
2 
3class Test:
4 
5 def __init__(self):
6 print("Constructor Execution.")
7 
8 def __del__(self):
9 print("Destructor Execution.")
10 
11 
12list = [Test(), Test(), Test()]
13 
14del list
15 
16time.sleep(5)
17 
18print("End of application")
Output
Constructor Execution.
Constructor Execution.
Constructor Execution.
Destructor Execution.
Destructor Execution.
Destructor Execution.
End of application

Explanation

The list stores references to three different Test objects.

When del list is executed, the only references to all three objects are removed.

Each object now has a reference count of zero, so the destructor executes once for every object.

Garbage Collection vs Destructor

Feature Garbage Collection Destructor
Purpose Release Memory Cleanup Resources
Executed By Python Garbage Collector Python Automatically
When Executed Reference Count Becomes Zero Just Before Object Destruction
User Invocation No No
Main Work Destroy Object Close Files, Release Resources
📝 Key Takeaways
  • Garbage collection automatically destroys objects that are no longer referenced
  • An object becomes eligible for garbage collection when its reference count becomes zero
  • The __del__() destructor executes automatically just before an object is destroyed
  • Reference counting tracks how many references point to an object
  • sys.getrefcount() returns the current reference count, including one internal temporary reference

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8