What is __del__ in Python?

Python Tutorials

Summary: In this tutorial, we will learn what __del__ is in Python and when we should use it in our Python code.

__del__ in Python

__del__ is a reserved function in Python that is called when the last reference to an object is being deleted or goes out of scope.

It is similar to the destructor of C++ and is also known as the finalizer.

Example 1: When Object is Deleted Manually

class Car:
    def __init__(self):
        print("Building the Car")
        self.name = "Lamborghini"
        self.max_speed = "220 mph"
        
    def display(self):
        print(f"Name: {self.name}")
        print(f"Max Speed: {self.max_speed}")
        
    def __del__(self):
        print("Destroying the Car")
        
#creating object of the class
myCar = Car()

#calling the display function of the myCar object
myCar.display()

#manually deleting the object using the del keyword
del myCar

Output:

Building the Car
Name: Lamborghini
Max Speed: 220 mph
Destroying the Car

In this example, we create an object of type Car, display its properties and finally delete its only reference using the del keyword.

When the object is being destroyed, the __del__ method on the object is automatically invoked by Python (similar to __init__ which is called during the object creation).

It is important to note that “del x” doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when its reference count reaches zero.

Example 2: When Object goes Out of Scope

class Car:
    def __init__(self):
        print("Building the Car")
        self.name = "Lamborghini"
        self.max_speed = "220 mph"
        
    def display(self):
        print(f"Name: {self.name}")
        print(f"Max Speed: {self.max_speed}")
        
    def __del__(self):
        print("Destroying the Car")
        
#funtion to create an object of Car and display its properties        
def createObject():
    myCar = Car()
    myCar.display()

#calling the function
createObject()

Output:

Building the Car
Name: Lamborghini
Max Speed: 220 mph
Destroying the Car

Observe the output in this case, it similar to the previous example.

It is so because we have created an object inside the scope of the function and when the function’s scope ends (the current running scope changes) the object gets deleted and the __del__ function is invoked in response.

When to use __del__ in Python?

It is important to note that the __del__ method is called when the object is in the process of getting destroyed (not after getting destroyed), therefore the properties are still accessible within the __del__ method.

Since __del__ has access to the data members of the object, it should be to ensure the poper deletion of the object, so that no memory is leaked.

Example:

class App:
    def __init__(self):
        print("App Opened")
        
    def __del__(self):
        print("App closed")

class Phone:
    app = None
    
    def __init__(self):
        print("Switching on the Phone")
        self.__class__.app = App()
        
    def __del__(self):
        del self.__class__.app
        print("Switching off the Phone")
        

#creating an object of Phone
phone = Phone()

#deleting the object
del phone

Output:

Switching on the Phone
App Opened
App closed
Switching off the Phone

In this example, if we had not destroyed the phone’s property app inside the __del__ method, it would have remained in the memory, causing a memory leak.

One thought on “What is __del__ in Python?”

  1. I really appreciate you. Your explanations are both concise and very easy to understand. I added your website to bookmarks. Great work!

Leave a Reply to Alex Cancel reply

Your email address will not be published. Required fields are marked *