to close or not to close?

Moshe Zadka moshez at math.huji.ac.il
Tue Aug 1 02:15:35 EDT 2000


On 31 Jul 2000, [ISO-8859-1] François Pinard wrote:

> I came to consider it is a better form to _not_ close explicitely.  Cases
> where explicit close is really useful are rather unusual, in my experience.
> In which cases, an explicit `close' gets more meaningful, and less noisy.
> And even then, I much prefer `file = None' than `close(file)', because the
> former really represents my intent: I promise I will not use `file' anymore.
> I like to think that closing a file is a system concern, not a user concern.

Perhaps -- but it is not gureanteed that Python will *ever* close
the file. I think the best way is:


def f(file):
	fp = open(file)
	try:
		pass
	finally:
		fp.close()

This gives my programs a good measure of predictability.

--
Moshe Zadka <moshez at math.huji.ac.il>
There is no IGLU cabal.
http://advogato.org/person/moshez





More information about the Python-list mailing list