"file" does not work with the "with" statement!

Christian Heimes lists at cheimes.de
Thu Dec 10 05:59:55 EST 2009


Michele Simionato wrote:
> Python 2.5, but it could be an artifact of the way I am looking if a
> file is closed.
> I have subclassed the file builtin, added a .close method and it was
> not called by the
> "with" statement. This during debugging, but now I have found another
> reason to explain why I was
> running out of file descriptors, (I was opening too many connections
> to the db).
> It is entirely possible that the problem was not with the "with"
> statement.

In Python 2.5 you have to implement your own __enter__ and __exit__
methods if you subclass from file. The file.__exit__ function doesn't
call f.close(). The minor inconsistency has been fixed in Python 2.6.


Python 2.5:

static PyObject *
file_exit(PyFileObject *f, PyObject *args)
{
        PyObject *ret = file_close(f);
        if (!ret)
                /* If error occurred, pass through */
                return NULL;
        Py_DECREF(ret);
        /* We cannot return the result of close since a true
         * value will be interpreted as "yes, swallow the
         * exception if one was raised inside the with block". */
        Py_RETURN_NONE;
}

Python 2.6:

static PyObject *
file_exit(PyObject *f, PyObject *args)
{
        PyObject *ret = PyObject_CallMethod(f, "close", NULL);
        if (!ret)
                /* If error occurred, pass through */
                return NULL;
        Py_DECREF(ret);
        /* We cannot return the result of close since a true
         * value will be interpreted as "yes, swallow the
         * exception if one was raised inside the with block". */
        Py_RETURN_NONE;
}



More information about the Python-list mailing list