Skip to content

Commit e6652dd

Browse files
committed
Make PipedCompressionProgram.__init__ less complex
1 parent f9588b1 commit e6652dd

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/xopen/__init__.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ class _PipedCompressionProgram(io.IOBase):
165165
Read and write compressed files by running an external process and piping into it.
166166
"""
167167

168-
def __init__( # noqa: C901
168+
def __init__(
169169
self,
170170
filename: FileOrPath,
171171
mode="rb",
@@ -199,9 +199,10 @@ def __init__( # noqa: C901
199199
raise ValueError(
200200
f"compresslevel must be in {program_settings.acceptable_compression_levels}."
201201
)
202+
self._compresslevel = compresslevel
202203
self.fileobj, self.closefd = _file_or_path_to_binary_stream(filename, mode)
203-
filepath = _filepath_from_path_or_filelike(filename)
204-
self.name: str = str(filepath)
204+
self._path = _filepath_from_path_or_filelike(filename)
205+
self.name: str = str(self._path)
205206
self._mode: str = mode
206207
self._stderr = tempfile.TemporaryFile("w+b")
207208
self._threads_flag: Optional[str] = program_settings.threads_flag
@@ -215,7 +216,10 @@ def __init__( # noqa: C901
215216
threads = min(_available_cpu_count(), 4)
216217
self._threads = threads
217218

218-
if threads != 0 and self._threads_flag is not None:
219+
self._open_process()
220+
221+
def _open_process(self):
222+
if self._threads != 0 and self._threads_flag is not None:
219223
self._program_args += [f"{self._threads_flag}{self._threads}"]
220224

221225
# Setting close_fds to True in the Popen arguments is necessary due to
@@ -229,12 +233,12 @@ def __init__( # noqa: C901
229233
self.in_pipe = None
230234
self.in_thread = None
231235
self._feeding = True
232-
if "r" in mode:
236+
if "r" in self._mode:
233237
self._program_args += ["-c", "-d"] # type: ignore
234238
stdout = subprocess.PIPE
235239
else:
236-
if compresslevel is not None:
237-
self._program_args += ["-" + str(compresslevel)]
240+
if self._compresslevel is not None:
241+
self._program_args += ["-" + str(self._compresslevel)]
238242
stdout = self.fileobj # type: ignore
239243
try:
240244
self.process = subprocess.Popen(
@@ -249,7 +253,7 @@ def __init__( # noqa: C901
249253
self.fileobj.close()
250254
raise
251255
assert self.process.stdin is not None
252-
if "r" in mode:
256+
if "r" in self._mode:
253257
self.in_pipe = self.process.stdin
254258
# A python subprocess can read and write from pipes, but not from
255259
# Python in-memory objects. In order for a program to read from an

0 commit comments

Comments
 (0)