Scanning a file

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Oct 30 00:49:02 CEST 2005


On Sat, 29 Oct 2005 21:08:09 +0000, Tim Roberts wrote:

>>In any case, you are assuming that Python will automagically close the
>>file when you are done.
> 
> Nonsense.  This behavior is deterministic.  At the end of that line, the
> anonymous file object out of scope, the object is deleted, and the file is
> closed.

That is an implementation detail. CPython may do that, but JPython does
not -- or at least it did not last time I looked. JPython doesn't
guarantee that the file will be closed at any particular time, just that
it will be closed eventually.

If all goes well. What if you have a circular dependence and the file
reference never gets garbage-collected? What happens if the JPython
process gets killed before the file is closed? You might not care about
one file not being released, but what if it is hundreds of files?

In general, it is best practice to release external resources as soon as
you're done with them, and not rely on a garbage collector which may or
may not release them in a timely manner.

There are circumstances where things do not go well and the file never
gets closed cleanly -- for example, when your disk is full, and the
buffer is only written to disk when you close the file. Would you
prefer that error to raise an exception, or to pass silently? If you want
close exceptions to pass silently, then by all means rely on the garbage
collector to close the file.

You might not care about these details in a short script -- when I'm
writing a use-once-and-throw-away script, that's what I do. But it isn't
best practice: explicit is better than implicit.

I should also point out that for really serious work, the idiom:

f = file("parrot")
handle(f)
f.close()

is insufficiently robust for production level code. That was a detail I
didn't think I needed to drop on the original newbie poster, but depending
on how paranoid you are, or how many exceptions you want to insulate the
user from, something like this might be needed:

try:
    f = file("parrot")
    try:
        handle(f)
    finally:
        try:
            f.close()
        except:
            print "The file could not be closed; see your sys admin."
except:
    print "The file could not be opened."


-- 
Steven.




More information about the Python-list mailing list