to close or not to close?

Thomas Wouters thomas at xs4all.net
Mon Jul 31 19:05:33 EDT 2000


On Mon, Jul 31, 2000 at 02:48:02PM -0700, Grant Griffin wrote:

> Forgive me if this is a FAQ, but is it considered good Python form to close a
> file whose variable is just about to go out of scope (and thus be automatically
> closed)?  Or should one just omit that?

If you care about portability of your code, and the code in question is
frequently executed inside the script (like in a rapid for-loop), you'd best
close it yourself. In current CPython it won't cause any problem to omit the
close as long as you are certain the vrbl will go out of scope, but JPython
and possibly other implementations of Python use true garbage collection
(GC) rather than reference counting (RC). GC is usually fired periodically,
or when system resources run low, and somehow not all GC's see
filedescriptors as system resources ;) So something like this:

for x in [:256]: # or range(256) if you don't run experimental patches
	open("tempfile.%d"%x)

Will work just fine in CPython, having open at most 2 'tempfiles' at once
(in an interactive session, that is, otherwise it has just 1 open.) But the
same script under JPython, or a possible future CPython with true GC, will
run out of filedescriptors (or more likely: the max number of open files)
before the next GC run.

(The above script is not that silly an example; I've actually used it, with
larger numbers, to create a large number of testfiles ;-) The example is
easily fixed, as the resulting isn't used. Just change it to
'open(..).close()'. It's just a tad trickier if you want to do
'open().read()' :-)

Of course, if you don't plan on running the code inside a busy for loop,
you'll hardly notice.

No-I-didn't-say-CPython-will-grow-true-GC!-ly y'rs,
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list