]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-126565: Skip `zipfile.Path.exists` check in write mode (GH-126576) (#126643)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 10 Nov 2024 15:14:48 +0000 (16:14 +0100)
committerGitHub <noreply@github.com>
Sun, 10 Nov 2024 15:14:48 +0000 (15:14 +0000)
gh-126565: Skip `zipfile.Path.exists` check in write mode (GH-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.
(cherry picked from commit 160758a574d12bf0d965d8206136e7da4f4fd6c3)

Co-authored-by: Jan Hicken <janhicken@users.noreply.github.com>
Lib/zipfile/_path/__init__.py
Misc/NEWS.d/next/Library/2024-11-08-11-06-14.gh-issue-126565.dFFO22.rst [new file with mode: 0644]

index 8db5ef18d7c5b0142313049903688fcb9fca9313..645cfafdd623d911c5dcab252e34d9706bf1fc75 100644 (file)
@@ -303,7 +303,7 @@ class Path:
         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:
diff --git a/Misc/NEWS.d/next/Library/2024-11-08-11-06-14.gh-issue-126565.dFFO22.rst b/Misc/NEWS.d/next/Library/2024-11-08-11-06-14.gh-issue-126565.dFFO22.rst
new file mode 100644 (file)
index 0000000..2285857
--- /dev/null
@@ -0,0 +1 @@
+Improve performances of :meth:`zipfile.Path.open` for non-reading modes.