Re: __init__ and __del__

Guido.van.Rossum@cwi.nl
Tue, 18 May 1993 16:32:23 +0200

>From the responses so far I can conclude that having __init__
explicitly call the base class's __init__ is the best possible
solution, so let's move on to Chris' suggestion:

> By the way, will there be a __del__(self) method that is called at
> destruction time? My thought on this was that when python sees that an
> object should be garbage collected, it calls the object's __del__
> method (if any) before actually destroying it. Of course the
> interpreter would have to check the object's refcount after calling
> the function, as the method may have caused the object to be
> referenced by some other object.

The problem with this is, what to do if the __del__ call creates
another reference to the object? You can't delete it then since the
new reference would be dangling. But not deleting the object means
that the __del__ method may be called again later when the reference
count goes down to zero once again. Would this be a problem?

> I don't really have a good example of why you'd want this, other than
> for creating classes that keep track of how many instances of the
> class exist. Perhaps someone else can think of a good reason for
> having it. It just seems that if you have a function that is called at
> object creation that you should have one that is called at object
> destruction as well.

Actually, there are lots of situations where a class is used as a
wrapper around some "real-world" object (e.g. a window or a temporary
file or an audio device) that you would want to destroy (or restore to
a previous state) when the instance goes away. So yes, I think there
are many cases where this would be useful.

There's one problem with __del__, however: what if it raises an
exception? __del__ will be called implicitly from a DECREF(x)
statement in the C code, and I'm not going to add error checking to
all DECREF() statements. So these exceptions will have to be ignored.
In fact, there may already be an exception pending when DECREF() is
called, so it may have to save and restore the original exception.
Nasty!

One final thing to ponder: if we have a __del__ method, should the
interpreter guarantee that it is called when the program exits? (Like
C++, which guarantees that destructors of global variables are
called.) The only way to guarantee this is to go running around all
modules and delete all their variables. But this means that __del__
method cannot trust that any global variables it might want to use
still exist, since there is no way to know in what order variables are
to be deleted. Or is this not a useful feature?

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>