file closing
Skip Montanaro
skip at pobox.com
Fri May 23 09:58:52 EDT 2003
>> >> file('test.dat','w').write(chr(0)*1000000)
>> More precisely, it relies on reference counting. There's no cycle
>> which needs to be broken, so CPython's cyclical garbage collection
>> isn't involved.
Colin> Okay... so the reference count for the file handle drops to zero
Colin> immediately after execution of this instruction. Does this mean
Colin> an explicit close is being done before the next instruction? If
Colin> so then the two code snippets are functionally identical (with
Colin> the second being much shorter). Also is the close synchronous or
Colin> asynchronous?
Yes. In CPython (Jython has different semantics because it uses Java's
garbage collector), at the time the reference count drops to zero, the file
object's dealloc slot is called immediately. That code calls the object's
close method:
static void
file_dealloc(PyFileObject *f)
{
if (f->f_fp != NULL && f->f_close != NULL) {
Py_BEGIN_ALLOW_THREADS
(*f->f_close)(f->f_fp); <---- right here
Py_END_ALLOW_THREADS
}
Py_XDECREF(f->f_name);
Py_XDECREF(f->f_mode);
Py_XDECREF(f->f_encoding);
drop_readahead(f);
f->ob_type->tp_free((PyObject *)f);
}
which is the usual fclose() function.
Yes, the two code snippets are functionally identical. If they weren't,
we'd have heard about it long before now.
I don't know what you mean by "synchronous" vs. "asynchronous" in this
context.
That all being the case:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
...
Skip
More information about the Python-list
mailing list