Skip to content

Commit

Permalink
Add close_fileobj parameter to xopen
Browse files Browse the repository at this point in the history
  • Loading branch information
jdidion committed Dec 11, 2017
1 parent 1b77276 commit 6226687
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
v3.1.3 (dev)
------------
* Added `close_fileobj` parameters to `xopen()` to allow user to specify whether the file should be closed when the wrapper is closed.

v3.1.2 (2017.11.18)
-------------------
Expand Down
17 changes: 15 additions & 2 deletions xphyle/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,13 @@ def path(self):
return getattr(self, '_path', None)


class OpenFileWrapper(FileWrapper):
"""FileWrapper that does not close its underlying file.
"""
def _close(self) -> None:
pass


class BufferWrapper(FileWrapper):
"""Wrapper around a string/bytes buffer.
Expand Down Expand Up @@ -765,7 +772,7 @@ def xopen(
compression: CompressionArg = None, use_system: bool = True,
allow_subprocesses: bool = True, context_wrapper: bool = None,
file_type: FileType = None, validate: bool = True,
overwrite: bool = True, **kwargs
overwrite: bool = True, close_fileobj: bool = True, **kwargs
) -> FileLike:
"""
Replacement for the builtin `open` function that can also open URLs and
Expand Down Expand Up @@ -800,6 +807,9 @@ def xopen(
format guessed from the file extension or magic bytes.
overwrite: For files opened in write mode, whether to overwrite
existing files (True).
close_fileobj: When `path` is a file-like object / `file_type` is
FILELIKE, and `context_wrapper` is True, this determines whether to
close the underlying file object when closing the wrapper.
kwargs: Additional keyword arguments to pass to ``open``.
`path` is interpreted as follows:
Expand Down Expand Up @@ -1103,7 +1113,10 @@ def xopen(
elif file_type == FileType.BUFFER:
fileobj = BufferWrapper(fileobj, buffer, compression=compression)
else:
fileobj = FileWrapper(
file_wrapper_class = FileWrapper
if file_type == FileType.FILELIKE and not close_fileobj:
file_wrapper_class = OpenFileWrapper
fileobj = file_wrapper_class(
fileobj, name=name, mode=mode,compression=compression)

return fileobj
Expand Down

0 comments on commit 6226687

Please sign in to comment.