loader.py 495 B

123456789101112131415
  1. import importlib
  2. def load_function_or_class(path):
  3. """Load a function or class at runtime given a full path.
  4. Example of the path: mypkg.mysubpkg.myclass
  5. """
  6. class_data = path.split(".")
  7. if len(class_data) < 2:
  8. raise ValueError("You need to pass a valid path like mymodule.provider_class")
  9. module_path = ".".join(class_data[:-1])
  10. fn_or_class_str = class_data[-1]
  11. module = importlib.import_module(module_path)
  12. return getattr(module, fn_or_class_str)