Make load_module() return existing module if present in sys.modules
Otherwise the reload() builtin will not work correctly:
https://www.python.org/dev/peps/pep-0302/#specification-part-1-the-importer-protocol
--- a/cubicweb/__init__.py Mon Feb 06 15:43:19 2017 +0100
+++ b/cubicweb/__init__.py Wed Feb 08 10:31:26 2017 +0100
@@ -307,6 +307,13 @@
return pkgutil.ImpLoader(fullname, *modinfo)
def load_module(self, fullname):
+ try:
+ # If there is an existing module object named 'fullname' in
+ # sys.modules , the loader must use that existing module.
+ # Otherwise, the reload() builtin will not work correctly.
+ return sys.modules[fullname]
+ except KeyError:
+ pass
if fullname != 'cubes':
raise ImportError('No module named {0}'.format(fullname))
mod = sys.modules[fullname] = types.ModuleType(fullname, doc='CubicWeb cubes')
--- a/cubicweb/test/unittest_cubes.py Mon Feb 06 15:43:19 2017 +0100
+++ b/cubicweb/test/unittest_cubes.py Wed Feb 08 10:31:26 2017 +0100
@@ -93,6 +93,17 @@
from cubes.foo import bar
self.assertEqual(bar.baz, 1)
+ def test_reload_cube(self):
+ """reloading cubes twice should return the same module"""
+ CubicWebConfiguration.cls_adjust_sys_path()
+ import cubes
+ if PY2:
+ new = reload(cubes)
+ else:
+ import importlib
+ new = importlib.reload(cubes)
+ self.assertIs(new, cubes)
+
def test_import_legacy_cube(self):
"""Check that importing a legacy cube works when sys.path got adjusted.
"""