Scanning a file

Alex Martelli aleaxit at yahoo.com
Mon Oct 31 01:08:04 CET 2005


John J. Lee <jjl at pobox.com> wrote:

> aleaxit at yahoo.com (Alex Martelli) writes:
> [...]
> > If you're trying to test your code to ensure it explicitly closes all
> > files, you could (from within your tests) rebind built-ins 'file' and
> > 'open' to be a class wrapping the real thing, and adding a flag to
> > remember if the file is open; at __del__ time it would warn if the file
> > had not been explicitly closed.  E.g. (untested code):
> [...]
> 
> In general __del__ methods interfere with garbage collection, don't

Yes, cyclic gc only.

> they?  I guess in the case of file objects this is unlikely to be
> problematic (because unlikely to be any reference cycles), but I
> thought it might be worth warning people that in general this
> debugging strategy might get rather confusing since the __del__ could
> actually change the operation of the program by preventing garbage
> collection of the objects whose lifetime you're trying to
> investigate...

Yeah, but you'll find them all listed in gc.garbage for your perusal --
they DO get collected, but they get put in gc.garbage rather than FREED,
that's all.  E.g.:

>>> class a(object):
...   def __del__(self): print 'del', self.__class__.__name__
... 
>>> class b(a): pass
... 
>>> x=a(); y=b(); x.y=y; y.x=x
>>> del x, y
>>> gc.collect()
4
>>> gc.garbage
[<__main__.a object at 0x64cf0>, <__main__.b object at 0x58510>]

So, no big deal -- run a gc.collect() and parse through gc.garbage for
any instances of your "wrapper of file" class, and you'll find ones that
were forgotten as part of a cyclic garbage loop and you can check
whether they were explicitly closed or not.


Alex



More information about the Python-list mailing list