Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How does garbage collection work in Python?
Python automatically manages memory through garbage collection, which frees unused objects to prevent memory leaks. The garbage collector runs during program execution and is triggered when an object's reference count reaches zero.
How Reference Counting Works
Python tracks how many variables reference each object. When this count reaches zero, the object is automatically deleted ?
# Reference counting example a = 40 # Create object <40>, ref count = 1 b = a # Increase ref count of <40> to 2 c = [b] # Increase ref count of <40> to 3 del a # Decrease ref count of <40> to 2 b = 100 # Decrease ref count of <40> to 1 c[0] = -1 # Decrease ref count of <40> to 0 (object deleted)
Reference Count Changes
An object's reference count increases when ?
- It is assigned to a new variable
- It is placed in a container (list, tuple, or dictionary)
- It is passed to a function
The reference count decreases when ?
- A variable is deleted with
del - A variable is reassigned to another object
- A variable goes out of scope
Using the __del__ Method
Classes can implement the __del__() destructor method, which is called when an object 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(f"{class_name} destroyed")
# Create objects
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(f"IDs: {id(pt1)} {id(pt2)} {id(pt3)}")
# Delete references
del pt1
del pt2
del pt3 # Object destroyed when last reference is deleted
IDs: 140234567890432 140234567890432 140234567890432 Point destroyed
Checking Reference Count
You can check an object's reference count using sys.getrefcount() ?
import sys
numbers = [1, 2, 3]
print(f"Reference count: {sys.getrefcount(numbers)}")
another_ref = numbers
print(f"After assignment: {sys.getrefcount(numbers)}")
del another_ref
print(f"After deletion: {sys.getrefcount(numbers)}")
Reference count: 2 After assignment: 3 After deletion: 2
Cyclic References and gc Module
Python also handles circular references using a separate cyclic garbage collector ?
import gc
class Node:
def __init__(self, value):
self.value = value
self.ref = None
# Create circular reference
node1 = Node(1)
node2 = Node(2)
node1.ref = node2
node2.ref = node1
print(f"Objects before collection: {len(gc.get_objects())}")
# Remove our references
del node1, node2
# Force garbage collection
collected = gc.collect()
print(f"Objects collected: {collected}")
Objects before collection: 12842 Objects collected: 2
Conclusion
Python's garbage collection automatically manages memory through reference counting and cyclic garbage collection. Understanding this helps write more memory-efficient programs and explains when __del__() methods are called.
