Gregor Horvath wrote: > #!/usr/bin/python > class A(object): > def __init__(self): > print "init" > > def __del__(self): > print "del" > > test1.py > > #!/usr/bin/python > import test > > class B(object): > a = test.A() > > Running test1.py outputs: > > init > > the "del" is missing. > > I suppose the a object should be garbage collected!?
No, Python doesn't run the garbage collector when it is exiting. What it does is to delete all the globals from each module in turn. So: C:\Python24>python Python 2.4.2c1 (#66, Sep 21 2005, 15:16:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def __init__(self): ... print "init" ... def __del__(self): ... print "del called" ... >>> a = A() init >>> ^Z del called C:\Python24> In this case the del method is called as 'a' is deleted, but if you create a circular reference a does not get destroyed: >>> class A(object): ... def __init__(self): ... print "init" ... def __del__(self): ... print "del called" ... >>> a = A() init >>> a.ref = a >>> ^Z C:\Python24> What is less obvious is that new style classes always include circular references, so a class is never detroyed until the garbage collector runs. A.__mro__ is a tuple which includes A, and there is probably something else I've forgotten (for an empty and otherwise unreferenced class getrefcount(oldstyleclass) returns 2, getrefcount(newstyleclass) returns 5). Of course, if your __del__ method actually does get invoked during program exit you have to be pretty careful what you do: the chances are any global variables you used in __del__ have already been destroyed in particular any modules you imported may have been deleted. In short, don't rely on anything much being possible from __del__ called this way. -- http://mail.python.org/mailman/listinfo/python-list