My Python class defines __del__ but it is not called when I delete the object


The __del__ is magic method in Python. The magic methods that allow us to do some pretty neat tricks in object-oriented programming. They are also called Dunder methods. These methods are identified by two underscores (__) used as prefix and suffix.

In Python, we create an oject using the __new__() and initialize using __init__(). However, to destruct an object, we have __del__().

Example

Let us create and delete an object −

class Demo: def __init__(self): print("We are creating an object."); # destructor def __del__(self): print("We are deleting an object."); # Createing and deleting an object ob = Demo(); del ob;

Output

We are creating an object.
We are deleting an object.

Reasons

However, the reasons can be many if a class defines __del__ but not called when the object is deleted −

  • The del statement does not necessarily call __del__() − It simply decrements the object’s reference count, and if this reaches zero __del__() is called.

  • The __del__() method may be called a random time. − If your data structures contain circular links the reference counts will never go back to zero. Python runs an algorithm to detect such cycles, but the garbage collector might run sometime after the last reference to your data structure vanishes.

Fix the issue

Following is the fix −

  • Do not call __del__() directly − The_del__() should call close() and close() should make sure that it can be called more than once for the same object.

  • Avoid cyclical references − Use the weakref module to avoid cyclical references. It allows you to point to objects without incrementing their reference count. The weakref module can also be used to get the instances of a class

Updated on: 19-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements