Garbage collection

Duncan Booth duncan.booth at invalid.invalid
Tue Feb 19 04:15:20 EST 2008


Jarek Zgoda <jzgoda at o2.usun.pl> wrote:

> Ken napisa³(a):
> 
>> The good news is that you almost never have to do anything to clean up. 
>> My guess is that you might not even need to overload __del__ at all. 
>> People from a C++ background often mistakenly think that they have to
>> write destructors when in fact they do not.
> 
> Is that true assumption that __del__ has the same purpose (and same
> limitations, i.e. the are not guaranteed to be fired) as Java finalizer
> methods?
> 

Pretty much. If you have a __del__ method on an object then in the worst 
case the only thing that can be guaranteed is that it will be called zero, 
one or more than one times. (Admittedly the last of these only happens if 
you work at it).

If it is called then is may be either immediately the last reference to the 
object is lost, or it may be later when the garbage collector runs (and not 
necessarily the first next time the garbage collector runs).

The nasty case to watch for is when __del__ is called while the program is 
exiting: any global variables in the module may have already been cleared 
so you cannot be sure that you can reference anything other than attributes 
on the object being destroyed (and if you call methods on the same or other 
objects they may also find they cannot reference all their globals).

Fortunately cases when you actually need to use __del__ are very rare.



More information about the Python-list mailing list