destructors in python

Kelly Burkhart kburk at sky.net
Tue Sep 14 22:12:01 EDT 1999


My tests show that the python destructor __del__ does not quite work
the way I expect.  The following program illustrates:

class Foo:

    def __init__(self):
	print "Foo::__init__"

    def __del__(self):
	print "Foo::__del__"


for i in range(2):
    print "----------"
    f = Foo()

The output:

[kburk at speedy python]$ ./tstdestruct.py
----------
Foo::__init__
----------
Foo::__init__
Foo::__del__
Foo::__del__

I expected to see the first __del__ before the second __init__.

I can hypothesize as to why what I expected did not occur: Is the fact
that the __del__ of the first object comes after the next Foo is
created a consequence of f not going out of scope between iterations
of the for loop?  Or does the variable go out of scope but the garbage
collector is cheating by not destroying the object until it's good and
ready?

Can I be guaranteed that the destructor of an object will be invoked
whenever it is collected, and collection will happen "close" to where
the object goes out of scope?

Will python ever exit without destroying all objects it knows about
(assuming no reference count blunders in extensions).

Is the behavior of destructors a Python GC implementation detail?
Should I worry about a new garbage collector implementation changing
the behavior of destructor calls in future versions of Python?
(i.e. introducing Java-like lossage).

TIA

-- 
Kelly R. Burkhart
kburk at sky.net

MIDL error 0xc0000005: unexpected compiler problem. Try to find a work around.
  -- Microsoft IDL compiler error message




More information about the Python-list mailing list