[Tutor] Closing file objects when object is garbage collected?

Michael Langford mlangford.cs03 at gtalumni.org
Tue Feb 12 17:19:04 CET 2008

> How do I ensure that when an object is deleted by the garbage
> collector that the file objects contained within the object are
> closed, or collected by the garbage collector?

__del__ is called after the reference count gets to zero for an
object. You can explicitly call close on the file there if you're
worried you have a dangling reference to the file somewhere. I'd use
the class below first to help.

If you'd like to see when if your files are being closed, a class such
as this may help your debugging. Use it in the place of your file or
open call in the class that is at issue:

class LoudFile(file):
     """Shows when a file is closed"""
     def close(self):
         if self.closed:
            print "%s is now closed" % self.name

     def __del__(self):
           """shows when a file is garbage collected"""
           print "%s fileobject is being deleted" % self.name

> I'm having issues when I test my software on XP, but not Linux. When I
> run the progam it fails after running for a while but not at exactly
> the same point each time. It fails in one of two ways, the user
> interface either completely disappears, or gives a OS error message
> unhanded exception error.

Run the program from the pdb debugger (it comes installed with
python). Here is an excellent introduction to it:

It will allow you to poke around at the innards of your program right
as it dies.


Michael Langford
Phone: 404-386-0495
Consulting: http://www.RowdyLabs.com

More information about the Tutor mailing list