[Tutor] Replacement for __del__

Alan Gauld alan.gauld at btinternet.com
Tue May 19 20:27:16 CEST 2009


"David Stanek" <dstanek at dstanek.com> wrote 

>> But I think (someone confirms/contradicts?) there is no harm 
> in overloading a class's __del__ to accomplish additional tasks 
> such as deleting temp disk space/dirs/files that need to exist 
> only during object creation.
> 
> Incorrect. 

Why?

> implementation. By the time it's executed many of the resources that
> you want to clean up could have already been garbage collected. 

True, but the things Denis refers to - temp disk space etc - will 
never be garbage collected. The GC only tidies up the stuff in 
memory.

If the object, as seems to be the case here, creates a file on disk 
which it uses as a semaphore/lock then GC will leave that file 
on the disk. A __del__ would enable it to be removed.

> def __del__(self):
>    try:
>        self.f.close()
>    except:
>        pass

This is, I agree, pointless. but very different to:

def __ del__(self):
     try:
        os.remove(self.lockname)
     except: pass


Of course the question of whether using disk storage to indicate 
object lifetime is a good design pattern is another issue altogether!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list