Class destruction

Nils Oliver Kröger NO_Kroeger at
Wed Aug 22 20:46:26 CEST 2007

Hash: SHA1

Robert Dailey schrieb:
> Hi,
> I'm wondering where the most appropriate location is to cleanup class
> objects. For example, i have a file handle as an instance attribute in one
> of my classes and I need to call f.close() on it when the class object falls
> out of scope. Any ideas? I've tried __del__() but I don't remember this
> working for some reason. I might try it again later just to be positive.

__del__(self) is the perfectly right place for such cleanup ... it gets
called once your instance is either deleted explicitly by you or it's
handled by the garbage collector when there are no more references.

The possible problem why this did not work four you is, that the
destruction by the garbage collector cannot be predicted ... it may well
take some time. If you try to open the same file from another class
before yours gets cleaned you run into trouble.

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

The below code works fine:

    def __del__( self ):
        print "File closed"

Hope that helps ... Nils
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla -


More information about the Python-list mailing list