diff --git a/Lib/pkgutil.py b/Lib/pkgutil.py --- a/Lib/pkgutil.py +++ b/Lib/pkgutil.py @@ -445,18 +445,18 @@ def iter_importers(fullname=""): If no module name is specified, all top level importers are produced. """ if fullname.startswith('.'): msg = "Relative module name {!r} not supported".format(fullname) raise ImportError(msg) if '.' in fullname: # Get the containing package's __path__ pkg_name = fullname.rpartition(".")[0] - pkg = importlib.import_module(pkg) - path = getattr(sys.modules[pkg], '__path__', None) + pkg = importlib.import_module(pkg_name) + path = getattr(sys.modules[pkg.__name__], '__path__', None) if path is None: return else: yield from sys.meta_path path = sys.path for item in path: yield get_importer(item) diff --git a/Lib/test/test_pkgutil.py b/Lib/test/test_pkgutil.py --- a/Lib/test/test_pkgutil.py +++ b/Lib/test/test_pkgutil.py @@ -1,12 +1,13 @@ from test.support import run_unittest, unload, check_warnings import unittest import sys import imp +import importlib import pkgutil import os import os.path import tempfile import shutil import zipfile # Note: pkgutil.walk_packages is currently tested in test_runpy. This is @@ -182,16 +183,50 @@ class ExtendPathTests(unittest.TestCase) shutil.rmtree(dirname_0) shutil.rmtree(dirname_1) del sys.path[0] del sys.path[0] del sys.modules['foo'] del sys.modules['foo.bar'] del sys.modules['foo.baz'] + def test_iter_importers(self): + iter_importers = pkgutil.iter_importers + get_importer = pkgutil.get_importer + + pkgname = 'spam' + modname = 'eggs' + dirname = self.create_init(pkgname) + pathitem = os.path.join(dirname, pkgname) + fullname = '{}.{}'.format(pkgname, modname) + try: + self.create_submodule(dirname, pkgname, modname, 0) + + importlib.import_module(fullname) + + importers = list(iter_importers(fullname)) + expected_importer = get_importer(pathitem) + for finder in importers: + self.assertIsInstance(finder, importlib.machinery.FileFinder) + self.assertEqual(finder, expected_importer) + self.assertIsInstance(finder.find_module(fullname), + importlib.machinery.SourceFileLoader) + self.assertIsNone(finder.find_module(pkgname)) + + with self.assertRaises(ImportError): + list(iter_importers('invalid.module')) + + with self.assertRaises(ImportError): + list(iter_importers('.spam')) + finally: + shutil.rmtree(dirname) + del sys.path[0] + del sys.modules['spam'] + del sys.modules['spam.eggs'] + def test_mixed_namespace(self): pkgname = 'foo' dirname_0 = self.create_init(pkgname) dirname_1 = self.create_init(pkgname) self.create_submodule(dirname_0, pkgname, 'bar', 0) # Turn this into a PEP 420 namespace package os.unlink(os.path.join(dirname_0, pkgname, '__init__.py')) self.create_submodule(dirname_1, pkgname, 'baz', 1)