classification
Title: Allow *open* to accept file-like objects
Type: enhancement Stage:
Components: IO Versions: Python 3.4
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, christian.heimes, samwyse
Priority: normal Keywords:

Created on 2012-10-03 21:30 by samwyse, last changed 2012-10-03 21:42 by benjamin.peterson. This issue is now closed.

Messages (3)
msg171908 - (view) Author: Samwyse (samwyse) Date: 2012-10-03 21:30
I'm once again frustrated by a third-party module that only accepts filenames, not already-opened file-like objects.  This prevents me from passing in StringIO objects or any of the standard file streams.  Currently, *open()* function accepts strings or (in Python 3.X) integers.  I propose that *open()* accept "file-like" objects, either returning them unchanged, or by returning a wrapper object.  While there are many different types of file-like objects, they all have one characteristic in common: the presence of a .close() method.

A non-wrapped version of open() could be as simple as this:

  try:
    file = original_open(name, mode, buffering)
  except TypeError:
    if hasattr(name, 'close'):
        return name
    raise

Returning a wrapper object would be slightly more complicated, but would allow the wrapped object to remain open even after the wrapper is closed.
msg171909 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2012-10-03 21:34
So, this is supposed to be a kludge for 3rd-party libraries that don't support using file objects? Immediately calling open() isn't necessarily what such a library will do. It could process the path somehow. Anyway, it's not clear what the semantics of the wrapper open() would return would be.

I'm going to close this. If you want to push it, you can bring it up on the python-ideas mailing list.
msg171910 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2012-10-03 21:40
I've another argument against your proposal:

open() always wraps a operating system resource and not some Python object. At the lowest level open() interacts with a file descriptor (aka file handler on Windows). I don't like to break the promise.

Lot's of 3rd party extensions don't support file-like objects because they wrap C libraries that either need a path, a file descriptor or a FILE* pointer.
History
Date User Action Args
2012-10-03 21:42:20benjamin.petersonsetresolution: rejected
2012-10-03 21:40:58christian.heimessetstatus: open -> closed
2012-10-03 21:40:14christian.heimessetstatus: closed -> open

nosy: + christian.heimes
messages: + msg171910

resolution: rejected -> (no value)
2012-10-03 21:34:26benjamin.petersonsetstatus: open -> closed
versions: + Python 3.4, - Python 2.7, Python 3.5
nosy: + benjamin.peterson

messages: + msg171909

resolution: rejected
2012-10-03 21:30:08samwysecreate