|
| 1 | +import imp |
| 2 | +import json |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import types |
| 6 | + |
| 7 | +not_loaded = 'not loaded' |
| 8 | + |
| 9 | +def library_loader(module_name): |
| 10 | + #print("Loading %s" % module_name) |
| 11 | + fp, pathname, description = imp.find_module(module_name) |
| 12 | + module = imp.load_module(module_name, fp, pathname, description) |
| 13 | + return module |
| 14 | + |
| 15 | +class LazyModule(types.ModuleType): |
| 16 | + """Subclass of ModuleType that implements a custom __getattribute__ method |
| 17 | + to allow lazy-loading of attributes from slicer sub-modules.""" |
| 18 | + |
| 19 | + def __init__(self, name): |
| 20 | + types.ModuleType.__init__(self, name) |
| 21 | + self.__lazy_attributes = {} |
| 22 | + #print("__lazy_attributes: %s" % len(self.__lazy_attributes)) |
| 23 | + |
| 24 | + def _update_lazy_attributes(self, lazy_attributes): |
| 25 | + self.__lazy_attributes.update(lazy_attributes) |
| 26 | + for k in lazy_attributes: |
| 27 | + setattr(self, k, not_loaded) |
| 28 | + |
| 29 | + def __getattribute__(self, attr): |
| 30 | + value = types.ModuleType.__getattribute__(self, attr) |
| 31 | + #print("__getattribute__ %s" % (attr)) |
| 32 | + if value is not_loaded: |
| 33 | + module_name = self.__lazy_attributes[attr] |
| 34 | + |
| 35 | + module = library_loader(module_name) |
| 36 | + namespace = module.__dict__ |
| 37 | + |
| 38 | + # Load into 'namespace' first, then self.__dict__ (via setattr) to |
| 39 | + # prevent the warnings about overwriting the 'NotLoaded' values |
| 40 | + # already in self.__dict__ we would get if we just update |
| 41 | + # self.__dict__. |
| 42 | + for k, v in namespace.items(): |
| 43 | + if not k.startswith('_'): |
| 44 | + setattr(self, k, v) |
| 45 | + value = namespace[attr] |
| 46 | + return value |
| 47 | + |
| 48 | +def writeModuleAttributeFile(module_name, config_dir='.'): |
| 49 | + try: |
| 50 | + exec("import %s as module" % module_name) |
| 51 | + except ImportError as details: |
| 52 | + print("%s [skipped: failed to import: %s]" % (module_name, details)) |
| 53 | + return |
| 54 | + attributes = [] |
| 55 | + for attr in dir(module): |
| 56 | + if not attr.startswith('__'): |
| 57 | + attributes.append(attr) |
| 58 | + filename = os.path.join(config_dir, "%s.json" % module_name) |
| 59 | + with open(filename, 'w') as output: |
| 60 | + print("%s [done: %s]" % (module_name, filename)) |
| 61 | + output.write(json.dumps({"attributes":attributes}, indent=4)) |
| 62 | + |
| 63 | +def updateLazyModule(module, input_module_names=[], config_dir=None): |
| 64 | + if isinstance(module, basestring): |
| 65 | + if module not in sys.modules: |
| 66 | + print("updateLazyModule failed: Couldn't find %s module" % module) |
| 67 | + return |
| 68 | + module = sys.modules[module] |
| 69 | + if not isinstance(module, LazyModule): |
| 70 | + print("updateLazyModule failed: module '%s' is not a LazyModule" % module) |
| 71 | + return |
| 72 | + if isinstance(input_module_names, basestring): |
| 73 | + input_module_names = [input_module_names] |
| 74 | + if config_dir is None: |
| 75 | + config_dir = os.path.dirname(module.__path__[0]) |
| 76 | + for input_module_name in input_module_names: |
| 77 | + filename = os.path.join(config_dir, "%s.json" % input_module_name) |
| 78 | + with open(filename) as input: |
| 79 | + module_attributes = json.load(input)['attributes'] |
| 80 | + #print("Updating %s with %d attributes" % (filename, len(module_attributes))) |
| 81 | + module._update_lazy_attributes({attribute: input_module_name for attribute in module_attributes}) |
| 82 | + |
| 83 | + #print("Updated %s module with %d attributes from %s" % (module, len(module._LazyModule__lazy_attributes), input_module_name)) |
| 84 | + |
| 85 | +def createLazyModule(module_name, module_path, input_module_names=[], config_dir=None): |
| 86 | + |
| 87 | + thisModule = sys.modules[module_name] if module_name in sys.modules else None |
| 88 | + |
| 89 | + if isinstance(thisModule, LazyModule): |
| 90 | + # Handle reload case where we've already done this once. |
| 91 | + # If we made a new module every time, multiple reload()s would fail |
| 92 | + # because the identity of sys.modules['itk'] would always be changing. |
| 93 | + #print("slicer: Calling ctor of LazyModule") |
| 94 | + thisModule.__init__(module_name) |
| 95 | + else: |
| 96 | + print("slicer: Creating new LazyModule") |
| 97 | + thisModule = LazyModule(module_name) |
| 98 | + |
| 99 | + # Set the __path__ attribute, which is required for this module to be used as a |
| 100 | + # package |
| 101 | + setattr(thisModule, '__path__', module_path) |
| 102 | + |
| 103 | + sys.modules[module_name] = thisModule |
| 104 | + |
| 105 | + updateLazyModule(thisModule, input_module_names, config_dir) |
| 106 | + |
| 107 | + return thisModule |
0 commit comments