Message 56643 - Python tracker (original) (raw)

These objects are supposed to be drop-in replacements for file handles. Except in legacy code, the way you use a file handle is:

with function_to_create_fh as fh:

If these objects do not support the with protocol, the only way to use them is to refactor this code. That may not even be possible, e.g., if it is in a library, or it may not be desirable to refactor.

Even if you can refactor it, I don't think you can call these objects file-like objects if you can't use them like a file.

Note that in legacy code, you used to write:

fh = function_to_get_fh try: finally: fh.close()

If function_to_get_fh happens to return some other file-like object and not an actual file, this still works fine without any refactoring.

You wrote:

In Py3k, I don't think adding support for the 'with' statement to StringIO makes any sense, since the close() method does nothing.

So do you propse removing the close() method altogether? Of course the answer is "no", because then you could not use the object like a file. The same is true for the with protocol.

(I now retract the words "that needs to be closed" from my original comment. All file-like objects should support the with protocol, regardles of whether their close() method actually does anything.)