assuring class 'clean up' actions are carried out

gyro gyromagnetic at excite.com
Mon Jun 23 09:56:32 EDT 2003


Hi,
I have a class which manages file- and directory-related things for an 
application. A simplified example is shown by class 'C2' below.

I would like to use an object of this class in another class ('C1' below).
My objective is to make sure that the '_cleanup' method of object C2 is 
called when C1 is destroyed or garbage collected.

I tried the solution below, but I get the following error when I execute 
file c1.py:
"Exception exceptions.ImportError: 'No module named shutil' in <bound 
method C1.__del__ of <__main__.C1 object at 0x811561c>> ignored"

Moreover, the temp directory is not deleted.

If I put an explicit 'del c1' below 'c1 = C1()', the cleanup seems to 
work fine. However, if possible, I would rather not have to explicitly 
delete the C1 instance. Is there a way to assure that the _cleanup is 
done when an object of C1 is eliminated by Python's garbage collector?

Thanks for your help.

-g



--- c1.py ---

from c2 import C2

class C1(object):
     def __init__(self):
         self.C2 = C2()

     def __del__(self):
         del self.C2

if __name__ == "__main__":
     c1 = C1()

--- end c1.py ---

--- c2.py ---

import tempfile

class C2(object):
     def __init__(self):
         self._tempdir = tempfile.mkdtemp()

     def _cleanup(self):
         import shutil
         shutil.rmtree(self._tempdir)

     def __del__(self):
         self._cleanup()

--- end c2.py ---





More information about the Python-list mailing list