/circuits/core/loader.py

https://bitbucket.org/prologic/circuits/ · Python · 63 lines · 34 code · 16 blank · 13 comment · 10 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. This module implements a generic Loader suitable for dynamically loading
  6. components from other modules. This supports loading from local paths,
  7. eggs and zip archives. Both setuptools and distribute are fully supported.
  8. """
  9. import sys
  10. from inspect import getmembers, getmodule, isclass
  11. from .handlers import handler
  12. from .utils import safeimport
  13. from .components import BaseComponent
  14. class Loader(BaseComponent):
  15. """Create a new Loader Component
  16. Creates a new Loader Component that enables dynamic loading of
  17. components from modules either in local paths, eggs or zip archives.
  18. """
  19. channel = "loader"
  20. def __init__(self, auto_register=True, init_args=None,
  21. init_kwargs=None, paths=None, channel=channel):
  22. "initializes x; see x.__class__.__doc__ for signature"
  23. super(Loader, self).__init__(channel=channel)
  24. self._auto_register = auto_register
  25. self._init_args = init_args or tuple()
  26. self._init_kwargs = init_kwargs or dict()
  27. if paths:
  28. for path in paths:
  29. sys.path.insert(0, path)
  30. @handler("load")
  31. def load(self, name):
  32. module = safeimport(name)
  33. if module is not None:
  34. test = lambda x: isclass(x) \
  35. and issubclass(x, BaseComponent) \
  36. and getmodule(x) is module
  37. components = [x[1] for x in getmembers(module, test)]
  38. if components:
  39. TheComponent = components[0]
  40. component = TheComponent(
  41. *self._init_args,
  42. **self._init_kwargs
  43. )
  44. if self._auto_register:
  45. component.register(self)
  46. return component