Class destruction

Marshall T. Vandegrift llasram at gmail.com
Wed Aug 22 19:06:51 EDT 2007


Nils Oliver Kröger <NO_Kroeger at gmx.de> writes:

> If you want to "reuse" the file, you will have to delete your classes
> instance explicitly using the del statement ... this will also call
> the destructor.

Sometimes, but not always.  The `del' statement simple removes the
reference to the instance and decrements its reference count.  The
__del__() routine for the instance still only gets called whenever the
object is actually garbage collected.  Furthermore, the Python Reference
Manual notes that:

    Circular references which are garbage are detected when the option
    cycle detector is enabled (it's on by default), but can only be
    cleaned up if there are no Python-level __del__() methods involved.
    [http://docs.python.org/ref/customization.html]

The proper way to handle the case presented by the OP is for the class
to expose a close()-like method and/or -- for use with Python 2.5 and
later -- implement the methods of the context manager protocol
[http://docs.python.org/ref/context-managers.html].  The following code
supports basic usage:

    def close(self):
        self._file.close()
        print "File closed"

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        self.close()
        return False

Then the users of this class can freely do any of:

    f = fout(filename)
    ...
    f.close()

    with fout(filename) as f:
        ...

    with closing(fout(filename)) as f:
        ...

HTH,

-Marshall




More information about the Python-list mailing list