Unbound names in __del__
Michael Hoffman
cam.ac.uk at mh391.invalid
Fri Jun 17 03:40:18 EDT 2005
Torsten Bronger wrote:
> When my __del__ methods are called because the program is being
> terminated, I experience difficulties in calling functions that I
> need for a clean shutdown of my instances. So far, there has been
> only one of these functions, and a class-local alias solved the
> problem. However, now there are many of them.
__del__ is messy and I avoid it whenever possible. Make sure you read
all the caveats and warnings on these pages:
http://www.python.org/doc/ref/customization.html
http://www.python.org/doc/lib/module-gc.html
Most importantly, "It is not guaranteed that __del__() methods are
called for objects that still exist when the interpreter exits."
> Or do you know a cleaner solution? For example, if I have
>
> import vpp43
>
> would it help to say
>
> def __init__(self):
> __vpp43 = vpp43
> ...
>
> to guarantee that I can access all the routines in vpp43 in the
> __del__ method?
A similar idiom is found in the standard library (e.g. tempfile.py):
# Cache the unlinker so we don't get spurious errors at
# shutdown when the module-level "os" is None'd out. Note
# that this must be referenced as self.unlink, because the
# name TemporaryFileWrapper may also get None'd out before
# __del__ is called.
unlink = _os.unlink
def close(self):
if not self.close_called:
self.close_called = True
self.file.close()
self.unlink(self.name)
def __del__(self):
self.close()
--
Michael Hoffman
More information about the Python-list
mailing list