Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8593a75

Browse files
committed
Fix importlib.machinery.PathFinder.find_module() to essentially skip over None
entries in sys.path_importer_cache. While this differs from semantics in how __import__ works, it prevents any implicit semantics from taking hold with users.
1 parent 0e31454 commit 8593a75

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

Lib/importlib/_bootstrap.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -661,9 +661,10 @@ def find_module(cls, fullname, path=None):
661661
finder = cls._path_importer_cache(entry)
662662
except ImportError:
663663
continue
664-
loader = finder.find_module(fullname)
665-
if loader:
666-
return loader
664+
if finder:
665+
loader = finder.find_module(fullname)
666+
if loader:
667+
return loader
667668
else:
668669
return None
669670

Lib/importlib/test/import_/test_path.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,25 @@ def test_path_hooks(self):
5555
self.assert_(path in sys.path_importer_cache)
5656
self.assert_(sys.path_importer_cache[path] is importer)
5757

58+
def test_path_importer_cache_has_None(self):
59+
# Test that if sys.path_importer_cache has None that None is returned.
60+
clear_cache = {path: None for path in sys.path}
61+
with util.import_state(path_importer_cache=clear_cache):
62+
for name in ('asynchat', 'sys', '<test module>'):
63+
self.assert_(machinery.PathFinder.find_module(name) is None)
64+
65+
def test_path_importer_cache_has_None_continues(self):
66+
# Test that having None in sys.path_importer_cache causes the search to
67+
# continue.
68+
path = '<test path>'
69+
module = '<test module>'
70+
importer = util.mock_modules(module)
71+
with util.import_state(path=['1', '2'],
72+
path_importer_cache={'1': None, '2': importer}):
73+
loader = machinery.PathFinder.find_module(module)
74+
self.assert_(loader is importer)
75+
76+
5877

5978
class DefaultPathFinderTests(unittest.TestCase):
6079

0 commit comments

Comments
 (0)