assuring class 'clean up' actions are carried out
tjreedy at udel.edu
Mon Jun 23 19:26:23 CEST 2003
"gyro" <gyromagnetic at excite.com> wrote in message
news:3ef70710 at news.ColoState.EDU...
> I have a class which manages file- and directory-related things for
> application. A simplified example is shown by class 'C2' below.
> I would like to use an object of this class in another class ('C1'
> My objective is to make sure that the '_cleanup' method of object C2
> called when C1 is destroyed or garbage collected.
To 'make sure', you must be explicit.
> I tried the solution below, but I get the following error when I
> file c1.py:
> "Exception exceptions.ImportError: 'No module named shutil' in
> method C1.__del__ of <__main__.C1 object at 0x811561c>> ignored"
> Moreover, the temp directory is not deleted.
When Python exits, it attempts to do some version-dependent,
source-code-documented cleanup in some arbitrary order. It appears
that shutil gets deleted first.
> If I put an explicit 'del c1' below 'c1 = C1()', the cleanup seems
> work fine. However, if possible, I would rather not have to
> delete the C1 instance.
You get what you pay for.
> Is there a way to assure that the _cleanup is
> done when an object of C1 is eliminated by Python's garbage
gc can and should only collect unreachable objects -- refcount 0 or
part of detached cycle. As long as global name c1 is bound to C1
instance, neither is true, and the instance will continue to exist,
Terry J. Reedy
More information about the Python-list