Skip to content

Commit e1bdecb

Browse files
authored
[3.10] bpo-45183: don't raise an exception when calling zipimport.zipimporter.find_spec() when the zip file is missing and the internal cache has been reset (GH-28435) (#28438)
This can occur when the zip file gets deleted, you call zipimport.zipimporter.invalidate_cache(), and then try to use zipimport.zipimporter.find_spec() (i.e. you left the zip file path on sys.path). (cherry picked from commit 209b703) Co-authored-by: Brett Cannon <[email protected]>
1 parent 397dad4 commit e1bdecb

File tree

4 files changed

+7
-3
lines changed

4 files changed

+7
-3
lines changed

Lib/test/test_zipimport.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,9 @@ def testInvalidateCaches(self):
547547
# Check that the cached data is removed if the file is deleted
548548
os.remove(TEMP_ZIP)
549549
zi.invalidate_caches()
550-
self.assertIsNone(zi._files)
550+
self.assertFalse(zi._files)
551551
self.assertIsNone(zipimport._zip_directory_cache.get(zi.archive))
552+
self.assertIsNone(zi.find_spec("name_does_not_matter"))
552553

553554
def testZipImporterMethodsInSubDirectory(self):
554555
packdir = TESTPACK + os.sep

Lib/zipimport.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ def invalidate_caches(self):
334334
_zip_directory_cache[self.archive] = self._files
335335
except ZipImportError:
336336
_zip_directory_cache.pop(self.archive, None)
337-
self._files = None
337+
self._files = {}
338338

339339

340340
def __repr__(self):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Have zipimport.zipimporter.find_spec() not raise an exception when the underlying zip
2+
file has been deleted and the internal cache has been reset via
3+
invalidate_cache().

Python/importlib_zipimport.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ const unsigned char _Py_M__zipimport[] = {
548548
0,106,1,131,1,124,0,95,2,124,0,106,2,116,3,124,
549549
0,106,1,60,0,87,0,100,1,83,0,4,0,116,4,121,
550550
35,1,0,1,0,1,0,116,3,160,5,124,0,106,1,100,
551-
1,161,2,1,0,100,1,124,0,95,2,89,0,100,1,83,
551+
1,161,2,1,0,105,0,124,0,95,2,89,0,100,1,83,
552552
0,119,0,41,2,122,41,82,101,108,111,97,100,32,116,104,
553553
101,32,102,105,108,101,32,100,97,116,97,32,111,102,32,116,
554554
104,101,32,97,114,99,104,105,118,101,32,112,97,116,104,46,

0 commit comments

Comments
 (0)