destructors order not guaranteed?

Alex Martelli aleaxit at yahoo.com
Wed Nov 1 13:10:48 EST 2000


"Rainer Deyke" <root at rainerdeyke.com> wrote in message
news:mVEL5.145181$g6.66741497 at news2.rdc2.tx.home.com...
> "William S. Lear" <rael at see.sig.com> wrote in message
> news:87snpduoxg.fsf at lisa.zopyra.com...
> > I don't see why it is not possible to "unwind" objects using a simple
> > stack of object pointers, but then I don't know the Python interpreter
> > internals.
>
> You can explicitly control the lifetime of objects by using del.  You can

"Not really", or, rather "only up to a point".  All that the del
statement does is remove a specific _reference_ to the object;
if other references persist, the object stays alive.  In a way,
with del, you explicitly control "the lifetime of *references*",
but only implicitly/indirectly does that affect the lt of *objects*.

> also reference the objects through a utility object which defines __del__
to
> delete the objects it references in order (which can be automated).

Could you please clarify/expand this idea?  Do you mean NOT
using
    a='foo'
    b='bar'
etc, but rather
    k=LifoDestroyer()
    k.a='foo'
    k.b='bar'
etc?  If so, then, yes, you can indeed easily design a LifoDestroyer
class that will (in __setattr__) take into account the order in
which attributes are added and (in __del__) use that order
to determine in which order the references are released, e.g.:

class LifoDestroyer:
    def __init__(self):
        self.__atrs=[]
    def __setattr__(self, name, value):
        if not name in self.__atrs:
            self.__atrs.append(name)
        self.__dict__[name] = value
    def __del__(self):
        self.__atrs.reverse()
        for name in self.__atrs:
            del self.__dict__[name]

Is this the desired semantics?  (Why?  I still can't fathom
what possible advantage this could give...).  Or is it:

    def __setattr__(self, name, value):
        if name in self.__atrs:
            self.__atrs.remove(name)
        self.__atrs.append(name)
        self.__dict__[name] = value

so that the order of _latest_ (rather than _earliest_)
binding of attribute-names is what gets reversed to
give unbinding-order...?  (here, too, I'm not sure I
see the advantage, but still it seems to make slightly
more sense...).


Alex






More information about the Python-list mailing list