From 63dae287035c9670c0622eefc9a19e0dc05c299f Mon Sep 17 00:00:00 2001 From: Andreas Sandberg Date: Mon, 3 Jun 2013 13:51:03 +0200 Subject: base: Make the Python module loader PEP302 compliant The custom Python loader didn't comply with PEP302 for two reasons: * Previously, we would overwrite old modules on name conflicts. PEP302 explicitly states that: "If there is an existing module object named 'fullname' in sys.modules, the loader must use that existing module". * The "__package__" attribute wasn't set. PEP302: "The __package__ attribute must be set." This changeset addresses both of these issues. --- src/python/importer.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'src/python') diff --git a/src/python/importer.py b/src/python/importer.py index 90fbae8b4..fa26080e5 100644 --- a/src/python/importer.py +++ b/src/python/importer.py @@ -54,8 +54,12 @@ class CodeImporter(object): import imp import os import sys - mod = imp.new_module(fullname) - sys.modules[fullname] = mod + + try: + mod = sys.modules[fullname] + except KeyError: + mod = imp.new_module(fullname) + sys.modules[fullname] = mod try: mod.__loader__ = self @@ -68,6 +72,9 @@ class CodeImporter(object): if os.path.basename(srcfile) == '__init__.py': mod.__path__ = fullname.split('.') + mod.__package__ = fullname + else: + mod.__package__ = fullname.rpartition('.')[0] mod.__file__ = srcfile exec code in mod.__dict__ -- cgit v1.2.3