destructors order not guaranteed?

Helen Dawson helend at accessone.com
Sun Nov 5 02:32:58 EST 2000


Here's the shortened version of Alex's post:

It can't be done, it can't be done, nobody wants it any
way, it can't be done, it can't be done.

Here's how you do it.

Okay, I'm just kidding. But the truth in that kidding is
that I suspect that your solution - a stack class with
a new() method, that records objects in order, and
deletes them in reverse order is exactly what was
requested.

Yes, if other objects have references to them, they
won't get destroyed. You know what - that's okay.
For those times when LIFO delete order matters
it will invariably be true that there are no other
references to them.

I suspect that the original poster would now want
to phrase his request as:

"I wish Python automatically dealt with local
variables in the way that Alex's Stack() class
does"

Python programmers that come from a C++
background, like myself, probably intuitively
assume that it behaves like that. I did. I
appreciate this discussion because I now have
a better understanding of how it does behave,
and why.

Bruce Dawson - comments at cygnus-software.com

Alex Martelli wrote:
One or two lines deleted...

> Instead of
>     a = instack(AClass(23, "foo"))
>     b = instack(BClass(42, "bar"))
> you would do, say:
>     stack = Stack()    # only in functions that want LIFO stuff!
>     a = stack.new(AClass(23, "foo"))
>     b = stack.new(BClass(42, "bar"))
> and, by convention, *never* take another reference to the
> object denoted by 'stack'.  The "real destructor" would not
> be __del__, but any method (able to be called without args)
> of the object that is new's first argument, with a default,
> of, say, 'finalize' (you could explicitly supply a different
> name as a second argument to .new -- also a tuple of args
> to use when calling that method, if you wish to be able
> to use non-callable-without-args methods or similar stuff).
>
> What this would ensure is: when the 'stack' object goes
> away, all the 'destructors' on the objects that were
> registered with it are called, in LIFO order.  That's it.




More information about the Python-list mailing list