Add import sub modules
+import pkgutil
+
+
class ImportStringCache(dict):
def __missing__(self, key):
if '.' not in key:
@@ -18,10 +21,24 @@ _cache = ImportStringCache()
def import_string(path):
- """
- Path must be module.path.ClassName
+ """Path must be module.path.ClassName
>>> cls = import_string('experiments.models.Experiment')
"""
result = _cache[path]
return result
+
+
+def import_submodules(context, root_module, path):
+ """Import all submodules and register them in the ``context`` namespace.
+
+ >>> import_submodules(locals(), __name__, __path__)
+ """
+ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'):
+ # this causes a Runtime error with model conflicts
+ # module = loader.find_module(module_name).load_module(module_name)
+ module = __import__(module_name, globals(), locals(), ['__name__'])
+ for k, v in vars(module).items():
+ if not k.startswith('_'):
+ context[k] = v
+ context[module_name] = module
