destructors order not guaranteed?
Alex Martelli
aleaxit at yahoo.com
Mon Oct 30 14:41:35 EST 2000
"Gagan Saksena" <gagan at netscape.com> wrote in message
news:39FDBC9E.5030204 at netscape.com...
> I was exploring the possibility of writing excursion classes in Python
What's an excursion class?
> but was disappointed to learn that the destructors order didn't seem to
> be consistent. Here is a minimal case to show this anomaly--
Local namespaces, and global (module) namespaces, do indeed
obey different rules regarding the order in which their entries are
removed.
Further, I do not believe that order is something you can rely
upon, anyway. Consider a "global namespace". It is, in fact,
a dictionary. When the dictionary itself (i.e., the namespace)
is gone, it will 'decref' (decrement the reference count of) its
entries in some order -- but that order is probably going to
be the one of the dictionary keys ("variable names") themselves.
*and the order of dictionary keys is clearly documented to
be arbitrary and NOT to be relied upon*... a consequence
of the use of hashing for dictionaries (which is required for
speed reasons). So, the order in which the variables are
removed may well turn out to be platform-dependent, to
depend on what _other_ variables are around, whatever;
definitely *NOT* something you can rely on in any way.
If you *do* need to impose an order, "object X _must_
not be deleted before object _Y_" -- it's easy: just
add to object _Y_ an attribute which refers to object
_X_! As soon as object _Y_ is alive, you can thus be
sure that object _X_ will be alive too. If both are
destroyed, it *WILL* assuredly be in the order: Y
first, X later.
Doing it for an arbitrary grouping of objects (i.e., all
the instances of a given class) is trickier. Basically
I think this is one of the many tricky system level
things that you cannot do without *weak references*,
references that will let you indicate a given object
*as long as that given object exists*, but *will go
away if that object disappears, rather than keeping
it alive*. Those are not built-in in Python, you have
to supply them separately. See, e.g.:
http://www.faqts.com/knowledge-base/view.phtml/aid/4484/fid/538/lang/
(though the link to the critical 'refhack' module it
needs seems broken, sigh).
Alex
More information about the Python-list
mailing list