assuring class 'clean up' actions are carried out

Terry Reedy tjreedy at udel.edu
Mon Jun 23 13:26:23 EDT 2003


"gyro" <gyromagnetic at excite.com> wrote in message
news:3ef70710 at news.ColoState.EDU...
> 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.

To 'make sure', you must be explicit.

> 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.

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
to
> work fine. However, if possible, I would rather not have to
explicitly
> 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
collector?

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 mailing list