From 209b7035f714dcc41df054b0b023e0b955d7e1a2 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Fri, 17 Sep 2021 16:48:17 -0700 Subject: [PATCH] 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) 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). --- Lib/test/test_zipimport.py | 3 ++- Lib/zipimport.py | 2 +- .../next/Library/2021-09-17-15-58-53.bpo-45183.Vv_vch.rst | 3 +++ 3 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2021-09-17-15-58-53.bpo-45183.Vv_vch.rst diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index 938674fcbd3..486200af703 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -548,8 +548,9 @@ def testInvalidateCaches(self): # Check that the cached data is removed if the file is deleted os.remove(TEMP_ZIP) zi.invalidate_caches() - self.assertIsNone(zi._files) + self.assertFalse(zi._files) self.assertIsNone(zipimport._zip_directory_cache.get(zi.archive)) + self.assertIsNone(zi.find_spec("name_does_not_matter")) def testZipImporterMethodsInSubDirectory(self): packdir = TESTPACK + os.sep diff --git a/Lib/zipimport.py b/Lib/zipimport.py index c55fec6aa1c..25eaee9c0f2 100644 --- a/Lib/zipimport.py +++ b/Lib/zipimport.py @@ -334,7 +334,7 @@ def invalidate_caches(self): _zip_directory_cache[self.archive] = self._files except ZipImportError: _zip_directory_cache.pop(self.archive, None) - self._files = None + self._files = {} def __repr__(self): diff --git a/Misc/NEWS.d/next/Library/2021-09-17-15-58-53.bpo-45183.Vv_vch.rst b/Misc/NEWS.d/next/Library/2021-09-17-15-58-53.bpo-45183.Vv_vch.rst new file mode 100644 index 00000000000..f3194b34318 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-09-17-15-58-53.bpo-45183.Vv_vch.rst @@ -0,0 +1,3 @@ +Have zipimport.zipimporter.find_spec() not raise an exception when the underlying zip +file has been deleted and the internal cache has been reset via +invalidate_cache().