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

Diez B. Roggisch deets at nospam.web.de
Thu Dec 10 05:35:18 EST 2009


Michele Simionato wrote:

> On Dec 10, 11:04 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> Are you sure? For me on python2.5, it works as advertised:
>>
>> from __future__ import with_statement
>>
>> def test(outf):
>> with outf:
>> outf.write("test\n")
>> try:
>> outf.write("test\n")
>> assert False, "Not closed"
>> except ValueError:
>> pass
>>
>> outf = open("/tmp/foo", "w")
>> test(outf)
>> outf = file("/tmp/bar", "w")
>> test(outf)
>>
>> Which Python do you use?
>>
>> Diez
> 
> Python 2.5, but it could be an artifact of the way I am looking if a
> file is closed.

The above ran on python2.5 for me, no hitch.

> 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.

Probably. Closing a file through with might not involve calling close() - it
might be implemented differently in __exit__.

So overload *that*, too.

Diez



More information about the Python-list mailing list