From 8447c703d1fd0107a52b15de7ce3a7056e1ec160 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Fri, 23 May 2014 12:30:37 -0400 Subject: [PATCH] Issue #14710: Fix both pkgutil.find_loader() and get_loader() to not raise an exception when a module doesn't exist. Thanks to Pavel Aslanov for the bug report. --- Lib/pkgutil.py | 4 +++- Lib/test/test_pkgutil.py | 14 ++++++++++++++ Misc/NEWS | 6 ++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Lib/pkgutil.py b/Lib/pkgutil.py index e42b6eb71f6..a54e9474d5b 100644 --- a/Lib/pkgutil.py +++ b/Lib/pkgutil.py @@ -456,6 +456,8 @@ def get_loader(module_or_name): """ if module_or_name in sys.modules: module_or_name = sys.modules[module_or_name] + if module_or_name is None: + return None if isinstance(module_or_name, ModuleType): module = module_or_name loader = getattr(module, '__loader__', None) @@ -487,7 +489,7 @@ def find_loader(fullname): # pkgutil previously raised ImportError msg = "Error while finding loader for {!r} ({}: {})" raise ImportError(msg.format(fullname, type(ex), ex)) from ex - return spec.loader + return spec.loader if spec is not None else None def extend_path(path, name): diff --git a/Lib/test/test_pkgutil.py b/Lib/test/test_pkgutil.py index 9704156a524..e0c8635de16 100644 --- a/Lib/test/test_pkgutil.py +++ b/Lib/test/test_pkgutil.py @@ -363,6 +363,20 @@ class ImportlibMigrationTests(unittest.TestCase): loader = pkgutil.get_loader(name) self.assertIsNone(loader) + def test_get_loader_None_in_sys_modules(self): + name = 'totally bogus' + sys.modules[name] = None + try: + loader = pkgutil.get_loader(name) + finally: + del sys.modules[name] + self.assertIsNone(loader) + + def test_find_loader_missing_module(self): + name = 'totally bogus' + loader = pkgutil.find_loader(name) + self.assertIsNone(loader) + def test_find_loader_avoids_emulation(self): with check_warnings() as w: self.assertIsNotNone(pkgutil.find_loader("sys")) diff --git a/Misc/NEWS b/Misc/NEWS index 6bee579ba98..cb99d561929 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -18,6 +18,12 @@ Core and Builtins Library ------- +- Issue #14710: pkgutil.get_loader() no longer raises an exception when None is + found in sys.modules. + +- Issue #14710: pkgutil.find_loader() no longer raises an exception when a + module doesn't exist. + - Issue #21538: The plistlib module now supports loading of binary plist files when reference or offset size is not a power of two.