loader.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import os
  2. import sys
  3. import imp
  4. class PikeLoader(object):
  5. def __init__(self, fullname, module_path):
  6. self.target_module_name = fullname
  7. self.module_path = module_path
  8. def is_package(self, fullname=None):
  9. """
  10. :param fullname: Not used, but required for Python 3.4
  11. """
  12. filename = os.path.basename(self.module_path)
  13. return filename.startswith('__init__')
  14. def augment_module(self, fullname, module):
  15. package, _, _ = fullname.rpartition('.')
  16. if self.is_package():
  17. module.__path__ = [self.module_path]
  18. module.__package__ = fullname
  19. else:
  20. module.__package__ = package
  21. return module
  22. def load_module(self, fullname):
  23. if self.target_module_name != fullname:
  24. raise ImportError('Cannot import module with this loader')
  25. if fullname in sys.modules:
  26. return sys.modules[fullname]
  27. module = self.load_module_by_path(fullname, self.module_path)
  28. sys.modules[fullname] = module
  29. return module
  30. def load_module_by_path(self, module_name, path):
  31. _, ext = os.path.splitext(path)
  32. module = None
  33. # FIXME(jmvrbanac): Get this working properly in PY3
  34. # Python 3 - Try to get the cache filename
  35. # if six.PY3:
  36. # compiled_filename = imp.cache_from_source(path)
  37. # if os.path.exists(compiled_filename):
  38. # path, ext = compiled_filename, '.pyc'
  39. # if ext.lower() == '.pyc':
  40. # module = imp.load_compiled(module_name, path)
  41. # elif ext.lower() == '.py':
  42. if ext.lower() == '.py':
  43. module = imp.load_source(module_name, path)
  44. if module:
  45. # Make sure we properly fill-in __path__ and __package__
  46. module = self.augment_module(module_name, module)
  47. return module