does python have useless destructors?

David Turner dkturner at telkomsa.net
Mon Jun 14 03:19:24 EDT 2004


Carl Banks <imbosol at aerojockey.invalid> wrote in message news:<zH0zc.89588$DG4.40492 at fe2.columbus.rr.com>...
> David Turner wrote:
> > Objects that define __del__ shall have a reference count, which is
> > incremented when names are bound to the object and decremented when
> > those names go out of scope.  The __del__ method is called when the
> > reference count reaches zero.  This mechanism is orthogonal to garbage
> > collection.
> 
> Are you aware that CPython already does this?

Yes, of course.  As I pointed out elsewhere, there is a weakness in
the current CPython implementation, in that exceptions grab extra
references to locals for the traceback.  A relatively minor code block
at the end of each exception handler could fix this problem.


> I assumed that you knew this, and I assumed that you were aware of the
> limitations of reference counting (in particular, that you cannot rely
> on a reference count ever going to zero).  That is why I took your
> statement to mean something else.

The limitations you refer to occur extremely infrequently in practice.
 Besides which, normally one does not create multiple references to
RAII objects.  Even if one did, I've never seen a situation in which a
cycle involving a RAII object was created.  I think it's unlikely that
this would ever occur, simply because RAII objects tend not to
reference anything that they don't explicitly own.  That's the whole
point of RAII, after all.

Bear in mind, we're not talking about reference-counting *everything*,
only those objects that *explicitly* define a __del__ method.  Those
are few and far between.


> But if I assumed incorrectly, then you should know this: reference
> counting simply doesn't take away the need to explicitly release
> resources, unless you don't care about robustness (that thing you
> claimed RAII is).  It works for the common case most of the time, but
> the danger always lurks that a reference could get trapped somewhere,
> or a cycle could arise.

It's far less likely that an unwary programmer creates a cycle
involving a RAII object (for the reasons I explained above) than that
he forgets to write a try/finally block.

At any rate, this criticism is beside the point: even if RAII doesn't
solve all problems, that's still not a good enough reason not to
consider it for inclusion in Python.

I have yet to hear a strong argument as to why it would be impossible
to implement on Python's current platforms.


> If you don't want that stuff happening, then you better use the
> explicit finally block, reference counted finalization or not.

Destruction, please.  Finalization is another thing altogether.


Regards
David Turner



More information about the Python-list mailing list