From 3a3ee826ba7e04e0fda105b9fcd3667e57d4182a Mon Sep 17 00:00:00 2001 From: Dat Nguyen Date: Mon, 8 Jul 2024 09:58:51 +0700 Subject: [PATCH] feat: Support dynamically import module from local path if import_module return nothing --- diqu/utils/module.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/diqu/utils/module.py b/diqu/utils/module.py index 2cacb34..882f4e6 100644 --- a/diqu/utils/module.py +++ b/diqu/utils/module.py @@ -1,8 +1,9 @@ -from importlib import import_module +from importlib import import_module, util +import sys from types import ModuleType from diqu.utils import exception - +from diqu.utils.log import logger def load_module(name: str, package: str = "diqu") -> ModuleType: """Import the module dynamically @@ -16,5 +17,18 @@ def load_module(name: str, package: str = "diqu") -> ModuleType: Returns: ModuleType: Imported module """ - with exception.handle_module_errors(name, f"{package}.{name}"): - return import_module(name=f".{name}", package=package) + module_name = f"{package}.{name}" + with exception.handle_module_errors(name, module_name): + try: + mod = import_module(name=f".{name}", package=package) + except: + mod = None + logger.debug(f"Import {module_name} module failed, trying local path...") + + if not mod: + spec = util.spec_from_file_location(module_name, f"{package.replace('.', '/')}/{name}.py") + mod = util.module_from_spec(spec) + sys.modules[module_name] = mod + spec.loader.exec_module(mod) + + return mod