/circuits/core/loader.py
Python | 63 lines | 34 code | 16 blank | 13 comment | 13 complexity | 54e62243a3029794dcef9355784eaddc MD5 | raw file
1# Package: loader 2# Date: 16th March 2011 3# Author: James Mills, jamesmills at comops dot com dot au 4 5""" 6This module implements a generic Loader suitable for dynamically loading 7components from other modules. This supports loading from local paths, 8eggs and zip archives. Both setuptools and distribute are fully supported. 9""" 10 11import sys 12from inspect import getmembers, getmodule, isclass 13 14from .handlers import handler 15from .utils import safeimport 16from .components import BaseComponent 17 18 19class Loader(BaseComponent): 20 """Create a new Loader Component 21 22 Creates a new Loader Component that enables dynamic loading of 23 components from modules either in local paths, eggs or zip archives. 24 """ 25 26 channel = "loader" 27 28 def __init__(self, auto_register=True, init_args=None, 29 init_kwargs=None, paths=None, channel=channel): 30 "initializes x; see x.__class__.__doc__ for signature" 31 32 super(Loader, self).__init__(channel=channel) 33 34 self._auto_register = auto_register 35 self._init_args = init_args or tuple() 36 self._init_kwargs = init_kwargs or dict() 37 38 if paths: 39 for path in paths: 40 sys.path.insert(0, path) 41 42 @handler("load") 43 def load(self, name): 44 module = safeimport(name) 45 if module is not None: 46 47 test = lambda x: isclass(x) \ 48 and issubclass(x, BaseComponent) \ 49 and getmodule(x) is module 50 components = [x[1] for x in getmembers(module, test)] 51 52 if components: 53 TheComponent = components[0] 54 55 component = TheComponent( 56 *self._init_args, 57 **self._init_kwargs 58 ) 59 60 if self._auto_register: 61 component.register(self) 62 63 return component