Order of constructor/destructor invocation

Reginald B. Charney news at charneyday.com
Tue Mar 5 00:37:37 EST 2002


In Python, are destructors defined to be invoked in reverse order of
constructors? 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"

The output I get using Python 2.2 is:

C:\WINDOWS>python "c:\my documents\t1.py"
Start of program
<HTML>
<BODY>
<?PHP
Body should appear before all destructors
?>
</HTML>
</BODY>

C:\WINDOWS>

The last two tags are out of order. They should have been </BODY> and then
</HTML>. I also ran this program with the names of the classes changed to
T1, T2, and T3 and the order of destructor invocation was correct: T3, T2,
T1. Thus, it seems to be a "order of name" issue. This problem also occurs
under Python 2.2 under Linux (SuSE 7.3). Under Python 1.5.2, the destructors
are never invoked.

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.

Reg.





More information about the Python-list mailing list