Skip to content

Commit

Permalink
pythongh-126565: Skip zipfile.Path.exists check in write mode
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
janhicken committed Nov 8, 2024
1 parent 06a8b0b commit 84cb5de
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/zipfile/_path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Calling :meth:`zipfile.Path.open` no longer checks for an existing file in
write mode. Checking for file existence in ZIP files opened in write mode is
particularly slow, because the list of members cannot be cached up-front. As
the check is irrelevant for the write mode any, it will no longer be performed
resulting in a performance improvement especially with ZIP files that have many
members.

0 comments on commit 84cb5de

Please sign in to comment.