[Tutor] Python __del__ method

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jul 11 20:24:27 EDT 2017


On 11/07/17 15:47, Jia Yue Kee wrote:
> I am new to Python and I came across the Python __del__ method 

The __del__() method is a bit of an oddity and often not
used in industrial strength Python code.

> if __name__ == "__main__":
>     x = Robot("Tik-Tok")
>     y = Robot("Jenkins")
>     z = x
>     del x
>     del z
>     del y
> 

> My question being why is that "Robot has been destroyed" 
> is only printed once in Case 2 

Because __del__() only got called once.
Which is really quite good, although you don't know which
object's del() was called!

The problem is that python does not promise to
call __del__() even when it is defined! It only promises
not to call it until all references are deleted.
So we can say when __del__() will not be called but
not when it will be called, if ever. The problem is
that __del__() is called by the garbage collector
when it actually collects the deleted object and that
could be a long time after the reference count goes
to zero, or possibly even never!

This means __del__() is of limited usefulness since
you can't rely on it being called. So you can't safely
use it as a destructor to release resources.

> ...after the del x and del z statements, the refcount 
> to the Robot object should reach zero and subsequently 
> triggers the __del__ method right?

Nearly.
It *might* trigger the __del__() method, eventually.
Or it might not, there is no guarantee. Mostly it
will get called, but you can't count on it.

I confess I don't fully understand the reasons why
it's been done that way, it just is...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list