reference counting and file objects

"Martin v. Löwis" martin at v.loewis.de
Tue May 17 15:07:13 EDT 2005


Paul Rubin wrote:
>>Consider the function above.  Do I need the fp.close(), or will the
>>file be closed automatically when fp goes out of scope and its
>>reference count drops to zero?
> 
> In CPython, fp gets closed when it leaves scope.

One issue is that when the function terminates through an exception,
the file stays open as long as the traceback is available, which
exists until the next exception is raised (and thus replaces this
traceback).

If the function terminates normally (i.e. through return), it is
as you say.

Regards,
Martin



More information about the Python-list mailing list