When are python classes and class attributes garbage collected?

In Python, a class is a blueprint for creating objects. It contains attributes and methods that define the behavior of objects created from it. Understanding when classes and their attributes are garbage collected is crucial for memory management.

class TutorialsPoint:
    def __init__(self):
        print("Welcome to TutorialsPoint.")
    
obj1 = TutorialsPoint()
Welcome to TutorialsPoint.

When are Python Classes Garbage Collected?

In Python, classes are garbage collected when there are no references to the class itself and no instances of the class exist. The garbage collector uses reference counting to determine when objects are eligible for collection.

A class becomes eligible for garbage collection when:

  • All instances of the class are deleted
  • No variables reference the class
  • The class is no longer accessible in the program scope

Example of Class Garbage Collection

import gc

class MyClass:
    def __init__(self, data):
        self.data = data

    def __del__(self):
        print(f"Object with data {self.data} is being garbage collected")

# Create two instances
obj1 = MyClass("first")
obj2 = MyClass("second")  

# Delete instances
del obj1
print("Deleted obj1")

del obj2
print("Deleted obj2")

# Force garbage collection
gc.collect()
Object with data first is being garbage collected
Deleted obj1
Object with data second is being garbage collected
Deleted obj2

What are Python Class Attributes?

Class attributes are variables defined inside a class but outside any method. They are shared by all instances of the class and belong to the class itself rather than to individual instances.

Example of Class Attributes

class Rectangle:
    side1 = 5  # class attribute 1
    side2 = 6  # class attribute 2
    
    def calculate_area(self):
        return self.side1 * self.side2
        
obj1 = Rectangle()
print("Area of the rectangle:", obj1.calculate_area())
print("Class attribute side1:", Rectangle.side1)
Area of the rectangle: 30
Class attribute side1: 5

When are Class Attributes Garbage Collected?

Class attributes are not directly garbage collected as long as the class exists. They are only collected when the entire class is deleted and has no references remaining.

Class attributes persist as long as:

  • The class definition exists in memory
  • There are references to the class or its instances
  • The class is accessible in the current scope

Example of Class Attribute Lifecycle

class Rectangle:
    side1 = 5  # class attribute 1
    side2 = 6  # class attribute 2
    
    def calculate_area(self):
        return self.side1 * self.side2
        
obj1 = Rectangle()
print("Area of the rectangle:", obj1.calculate_area())
print("Before deleting instance:", obj1.side1)

# Delete the instance (not the class)
del obj1

# Class attributes still exist because the class exists
print("Class attribute still accessible:", Rectangle.side1)

# Try to access deleted instance (will raise NameError)
try:
    print("After deleting instance:", obj1.side1)
except NameError as e:
    print("Error:", e)
Area of the rectangle: 30
Before deleting instance: 5
Class attribute still accessible: 5
Error: name 'obj1' is not defined

Key Points

Component Garbage Collected When Memory Impact
Class Instance No references remain Instance memory freed
Class Definition No instances + no references Class memory freed
Class Attributes Class is garbage collected Attribute memory freed with class

Conclusion

Python classes are garbage collected when no instances exist and no references to the class remain. Class attributes persist as long as the class definition exists in memory, making them useful for shared data across all instances.

Updated on: 2026-03-24T19:48:46+05:30

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements