does python have useless destructors?

David Turner dkturner at
Fri Jun 11 09:57:37 CEST 2004

Peter Hansen <peter at> wrote in message news:<ZtednbDcQ8EMhFTdRVn-sQ at>...
> Roger Binns wrote:
> > The correct answer of course is that the object itself
> > should be aware that it needs to be disposed of and that
> > real world resources can leak if it isn't.
> > 
> > Which brings us back in a full loop.  Currently objects
> > signify that they need disposing by having a destructor.
> > Why not "fix" that mechanism?
> Very likely the answer is "Because nobody has yet proposed
> a workable solution to the several conflicting requirements".
> Do _you_ have a solution?  If you do and it really works,
> it seems to me unlikely it would be ignored...

How about this:

1. Objects of classes that declare a __del__ method shall be referred
to as "deterministic" objects.  Such objects shall have a reference
count associated with.  The reference count shall be incremented
atomically each time an additional reference to the object is created.
 The reference count shall be decremented each time a name referring
to the object is deleted explicitly.  Except in the situation
described in (2) below, the reference count shall be decremented each
time a name referring to the object becomes inaccessible due to the
set of locals to which the name belongs becoming inaccessible.

2. Where an exception is raised from a suite which contains
deterministic locals, the stack traceback shall contain only weak
references to said locals.  However, the reference counts of
deterministic locals shall not be decreased until the path of
execution leaves the "except:" block that handles the exception.  When
this occurs, the deterministic locals shall be unreferenced, starting
at the deepest level of the traceback, and ending at most shallow
level of the traceback, with the most recently created objects at each
level being unreferenced first.

3. When the reference count of a deterministic object reaches zero,
the __del__ method of the object shall be called.

This will be a pain for the Jython implementers.  However, it is
doable.  Note that I never said the objects couldn't be garbage
collected, just that __del__ had to be called at certain well-defined
times.  What this will involve is the Jython compiler inserting a lot
of implicit try/finally constructs.

Can anyone see a reason why this scheme wouldn't work?

David Turner

More information about the Python-list mailing list