From 71ddd8d4f4ab200af870f0060d9ee8c6b7056681 Mon Sep 17 00:00:00 2001 From: Jan Hicken Date: Sun, 10 Nov 2024 15:57:24 +0100 Subject: [PATCH] Skip `zipfile.Path.exists` check in write mode (python/cpython#126576) When `zipfile.Path.open` is called, the implementation will check whether the path already exists in the ZIP file. However, this check is only required when the ZIP file is in read mode. By swapping arguments of the `and` operator, the short-circuiting will prevent the check from being run in write mode. This change will improve the performance of `open()`, because checking whether a file exists is slow in write mode, especially when the archive has many members. --- newsfragments/1a1928d.feature.rst | 1 + zipp/__init__.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 newsfragments/1a1928d.feature.rst diff --git a/newsfragments/1a1928d.feature.rst b/newsfragments/1a1928d.feature.rst new file mode 100644 index 0000000..2285857 --- /dev/null +++ b/newsfragments/1a1928d.feature.rst @@ -0,0 +1 @@ +Improve performances of :meth:`zipfile.Path.open` for non-reading modes. diff --git a/zipp/__init__.py b/zipp/__init__.py index cb4f42c..031d9d4 100644 --- a/zipp/__init__.py +++ b/zipp/__init__.py @@ -343,7 +343,7 @@ def open(self, mode='r', *args, pwd=None, **kwargs): if self.is_dir(): raise IsADirectoryError(self) zip_mode = mode[0] - if not self.exists() and zip_mode == 'r': + if zip_mode == 'r' and not self.exists(): raise FileNotFoundError(self) stream = self.root.open(self.at, zip_mode, pwd=pwd) if 'b' in mode: