Order of constructor/destructor invocation

Terry Reedy tejarex at yahoo.com
Fri Mar 8 09:28:24 EST 2002


"Reginald B. Charney" <news at charneyday.com> wrote in message
news:wI%h8.2623$ZR2.2434 at rwcrnsc52.ops.asp.att.net...
> Believe it or not, I was not trying to start a religious war. I was
trying
> to use a well-defined approach in one language to another language
that I
> thought was similar enough in structure to work in the same way.

As you have discovered, the Python interpreter does record the order
of object creation.  So do it yourself with a stack.  Start with
(untested)

class Finalize:    #this would be even simpler in 2.2 with
Finalize(class)
  def __init__(self):
    self.stack = []
  def __del__(self):
    self.stack.reverse()
    for pending in self.stack:
      pending.finalize()

Push = Finalize().stack.append

Now add Push(self) to the end of initializers that need a
corresponding finalizer and rename your finalizer methods 'finalize'
instead of '__del__'.  Now all the cleanup is invoked in the proper
order when the program ends.

Terry J. Reedy







More information about the Python-list mailing list