No destructor

Alex Martelli alex at magenta.com
Wed Aug 23 08:14:20 EDT 2000


"Paul Duffin" <pduffin at hursley.ibm.com> wrote in message
news:39A3A1AE.7238075C at hursley.ibm.com...
    [snip]
> I don't really see that the order in which you call the destructors is a
> problem. You simply need to define (and enforce) the rules about what the
> destructors can and cannot do in this case.

Unfortunately, what a destructor can reliably do, if any
reference the object holds may be invalid (and it has no
way to check), is "just about nothing".  E.g., can it
reliably call self.foo.close() on a file-like object to
which it's holding a self.foo ref? No, because self.foo
might have been part of a circular chain, including this
object 'self' as well, and have been finalized already.

At the very least, there should be a way to ask the system
whether any given reference one has is still valid/usable
(is to a non-yet-finalized object); so the call becomes
something like:

    def __del__(self):
        if self.foo and sys.valid(self.foo):
            self.foo.close()
            self.foo=None

But this is still far from satisfactory -- nor is it
all that useful; after all, self.foo will have to have
"self-closed" if it's happened to be finalized before
this 'self', so it will also similarly "self-close" if
it finalizes afterwards itself.  So the call to the
self.foo.close method cannot really be very important
to make; what *real* important tasks can __del__ really
perform if the references it holds can just have
disappeared from under its nose...?

There may be some cases in which an object is holding
references to things "it just knows for sure" _can't
possibly_ be part of a circular chain of references,
and *must* be "properly terminated" by the object as
they just can't be made capable of self-terminating.
But it doesn't seem that examples of this spring to
mind easily.


Alex






More information about the Python-list mailing list