Order of constructor/destructor invocation

Justin Sheehy justin at iago.org
Tue Mar 5 12:49:05 EST 2002


"Reginald B. Charney" <news at charneyday.com> writes:

> In Python, are destructors defined to be invoked in reverse order of
> constructors?

No.

> The following program illustrates the problem:
>
> class HTML:
>     def __init__(self): print "<HTML>"
>     def __del__(self):  print "</HTML>"
>
> class BODY:
>     def __init__(self): print "<BODY>"
>     def __del__(self):  print "</BODY>"
>
> class PHP:
>     def __init__(self): print "<?PHP "
>     def __del__(self):  print "?>"
>
> if __name__ == "__main__":
>     print "Start of program"
>     h = HTML()
>     b = BODY()
>     p = PHP()
>     print "Body should appear before all destructors"

A few comments:

  You really don't want to construct documents that way.  There are a
few good html generation libraries out there, and it is also easy to
roll your own.  Trying to generate documents as a side effect of
object destruction not only won't work, it is a really bad idea.

  Also, I have no idea what makes you think that you are able to know
anything about the order of the destructors.  All three of the
relevant objects here will lose their reference at the same time, so
the order of their destruction is even less determined than usual. <wink>

> Basically, I need to know if the order of destruction is guaranteed to be
> the reverse of construction when reference counts on the objects are the
> same (e.g., 1 on this case). Without this guarantee, I don't understand how
> Python can effectively use destructors - it falls into the same hole as
> Java. For me, this is a show-stopper.

This makes no sense.

When the reference count of an object is nonzero (e.g. 1), the
destructor will not be called at all because the object is not yet
eligible for reclamation.  Order doesn't even come into it.
Destroying an object before its reference count had dropped to zero
would be unsafe and not very sensical.

Perhaps you are using "destructors" to refer to some concept that is
different from what the rest of us use that word for?

-Justin

 





More information about the Python-list mailing list