Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is __del__ really a destructor?

Tags:

python

I do things mostly in C++, where the destructor method is really meant for destruction of an acquired resource. Recently I started with python (which is really a fun and fantastic), and I came to learn it has GC like java. Thus, there is no heavy emphasis on object ownership (construction and destruction).

As far as I've learned, the __init__() method makes more sense to me in python than it does for ruby too, but the __del__() method, do we really need to implement this built-in function in our class? Will my class lack something if I miss __del__()? The one scenario I could see __del__() useful is, if I want to log something when destroying an object. Is there anything other than this?

like image 734
RaGa__M Avatar asked Jun 16 '16 07:06

RaGa__M


3 Answers

In the Python 3 docs the developers have now made clear that destructor is in fact not the appropriate name for the method __del__.

object.__del__(self)

Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor.

Note that the OLD Python 3 docs used to suggest that 'destructor' was the proper name:

object.__del__(self)

Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.

From other answers but also from the Wikipedia:

In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII [Resource Acquisition Is Initialization]

So you should almost never be implementing __del__, but it gives you the opportunity to do so in some (rare?) use cases

like image 60
DomTomCat Avatar answered Oct 19 '22 13:10

DomTomCat


As the other answers have already pointed out, you probably shouldn't implement __del__ in Python. If you find yourself in the situation thinking you'd really need a destructor (for example if your class wraps a resource that needs to be explicitly closed) then the Pythonic way to go is using context managers.

like image 24
Florian Brucker Avatar answered Oct 19 '22 14:10

Florian Brucker


Is del really a destructor?

No, __del__ method is not a destructor, is just a normal method you can call whenever you want to perform any operation, but it is always called before the garbage collector destroys the object. Think of it like a clean or last will method.

like image 2
Netwave Avatar answered Oct 19 '22 13:10

Netwave