[Tutor] Replacement for __del__

A.T.Hofkamp a.t.hofkamp at tue.nl
Tue May 19 09:12:34 CEST 2009


Strax-Haber, Matthew (LARC-D320) wrote:
> A folder is created during object instantiation. This is necessary because
> multiple other methods depend on the existence of that folder, and in the
> future things may be running in parallel so it has to be there for the
> entire life of the object. Before the object is deleted, I want that temp
> folder to be deleted (ala shutil.rmtree). Is there a better way to do this?

It sounds like the object has 2 functions, namely managing your temp disk 
space, and the functionality of whatever the other methods of the object do.

I would suggest to split the temp disk space management to a seperate function 
that acts as a kind of main function:

def main():
   # make temp disk space

   obj = YourObject()
   obj.doit()  # Run the application

   # Application is finished here, cleanup the disk space.

This gives you explicit control when the disk space is cleared.

For a multi-threaded app you may want to wait somewhere until all threads are 
finished before proceeding to clean up the disk.

> Regardless of whether I should be using __del__, can anyone explain this to
> me (to satisfy curiosity):
> My class sub-types dict. In __init__, there is a call to
> self.update(pickle.load(<some file>)). For some reason, this triggers
> __del__. Why?

Somewhere an instance is created and garbage collected.

This is why you really don't want to use __del__. It is very good way to make 
your app behave strangely and give you weeks of debugging fun :p


Albert



More information about the Tutor mailing list