module_import_helper.py 2.5 KB

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