module_import_helper.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import importlib.util
  2. import logging
  3. import sys
  4. from types import ModuleType
  5. from typing import AnyStr
  6. def import_module_from_source(*, module_name: str, py_file_path: AnyStr, use_lazy_loader: bool = False) -> ModuleType:
  7. """
  8. Importing a module from the source file directly
  9. """
  10. try:
  11. existed_spec = importlib.util.find_spec(module_name)
  12. if existed_spec:
  13. spec = existed_spec
  14. if not spec.loader:
  15. raise Exception(f"Failed to load module {module_name} from {py_file_path}")
  16. else:
  17. # Refer to: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
  18. spec = importlib.util.spec_from_file_location(module_name, py_file_path)
  19. if not spec or not spec.loader:
  20. raise Exception(f"Failed to load module {module_name} from {py_file_path}")
  21. if use_lazy_loader:
  22. # Refer to: https://docs.python.org/3/library/importlib.html#implementing-lazy-imports
  23. spec.loader = importlib.util.LazyLoader(spec.loader)
  24. module = importlib.util.module_from_spec(spec)
  25. if not existed_spec:
  26. sys.modules[module_name] = module
  27. spec.loader.exec_module(module)
  28. return module
  29. except Exception as e:
  30. logging.exception(f"Failed to load module {module_name} from {py_file_path}: {str(e)}")
  31. raise e
  32. def get_subclasses_from_module(mod: ModuleType, parent_type: type) -> list[type]:
  33. """
  34. Get all the subclasses of the parent type from the module
  35. """
  36. classes = [x for _, x in vars(mod).items()
  37. if isinstance(x, type) and x != parent_type and issubclass(x, parent_type)]
  38. return classes
  39. def load_single_subclass_from_source(
  40. *, module_name: str, script_path: AnyStr, parent_type: type, use_lazy_loader: bool = False
  41. ) -> type:
  42. """
  43. Load a single subclass from the source
  44. """
  45. module = import_module_from_source(
  46. module_name=module_name, py_file_path=script_path, use_lazy_loader=use_lazy_loader
  47. )
  48. subclasses = get_subclasses_from_module(module, parent_type)
  49. match len(subclasses):
  50. case 1:
  51. return subclasses[0]
  52. case 0:
  53. raise Exception(f'Missing subclass of {parent_type.__name__} in {script_path}')
  54. case _:
  55. raise Exception(f'Multiple subclasses of {parent_type.__name__} in {script_path}')