Anonymous file closing

Terry Reedy tjreedy at
Fri Jun 11 18:08:22 CEST 2004

"Sergey Krushinsky" <skru at> wrote in message
news:40C9C547.9000204 at
> Duncan Booth wrote:
> >Yes it is closed, but it isn't well defined as to exactly when it is
> >closed. You can safely assume that the file will be closed sometime
> >the read returning and your program exiting.
> >
> Is it also true when file object exists inside a function? Like:

Short answer: yes.

Longer answer: the file object, like all Python objects, does not exist
inside anything except an implementation-defined-and-private 'dataspace'.
If there were a local name binding to the object, which there is not in the
example below, that binding, but not the object, would exist in the
function's local namespace during a particular invocation.

> def a():
>     text = open(filename, 'r').read()
>     ...

> It would be natural if the file object's memory were freed after a()
> completion.

'closing' the file, whatever that means for a particular system, and
freeing the object's memory are different operations, which have to occur
in that order.

In languages in which function locals are allocated on the stack just below
with the function's call frame, then deleting everything is trivial -- just
point the stack pointer above the expired call frame -- and therefore
natural.  For items on the heap, or in an abstract dataspace, it is not
natural at all, since they carry no information about when and where they
were created.  Moreover, if the function passes a refence to an object to a
surrounding context by writing/modify a non-local variable or by the return
statement, then freeing the object would be a mistake.  One of the traps in
C is the possibility to return a pointer to a local variable just as it is
'naturally' and automatically freed by the return.  CPython's reference
counting allows it to simulate C's 'natural' cleanup without deleting items
that should not be (because of other references).  But this is
intentionally not a requirement for all Python interpreters.

Terry J. Reedy

More information about the Python-list mailing list