Solution to finalisation problem [Re: fork()]

Greg Ewing greg.ewing at compaq.com
Sun Jun 13 23:47:22 CEST 1999


Tim Peters wrote:
> 
> the combo of
> finalizers, cycles and resurrection seems to be a philosophical mess even in
> languages that take it all <ahem> seriously.

Indeed, which leads me to believe that the idea of giving objects
a __del__ method is fundamentally flawed in the first place.

Fortunately, there *is* a way to do finalisation that avoids all
these problems. Instead of an object doing its own finalisation,
it designates some *other* object to do its finalisation on its
behalf after it is dead.

The benefits of this are:

(1) The object doing the finalisation is fully alive and operates
in a predictable environment.

(2) The object which triggered the finalisation is fully dead
(its memory has already been reclaimed by the time the finaliser
is called) and there is no possibility of it being resurrected.

In Python, it might look something like this from the
user's point of view:

class FileWrapper:
   # Example of a class needing finalisation.
   # Has an instance variable 'file' which needs
   # to be closed.
   def __init__(self, file):
      self.file = file
      register_finaliser(self, FileWrapperFinaliser(file))

class FileWrapperFinaliser:
   def __init__(self, file):
      self.file = file
   def __finalise__(self):
      self.file.close()

In this example, register_finaliser() is a new built-in
method which stores the object and its finaliser in some
special global dict. Whenever an object is reclaimed (either
by refcount or M&S) the dict is checked for a finaliser for
that object. If one is found, its __finalise__ method is
called and it is removed from the dict.

Note that the finaliser object shouldn't be given a reference
to the original object (doing so would prevent it from ever
becoming unreachable), but only enough information to enable
the finalisation to be carried out.

If a scheme like this were adopted, it should completely
replace the existing __del__ method mechanism, so that there
would be no difference between the finalisation of cyclic
and non-cyclic trash. As such it would have to wait for
Python 2.0.

A-final-solution-to-the-finalisation-problem,
Greg




More information about the Python-list mailing list