Skip to content

Commit

Permalink
feat: Support dynamically import module from local path if import_mod…
Browse files Browse the repository at this point in the history
…ule return nothing
  • Loading branch information
Dat Nguyen committed Jul 8, 2024
1 parent 7762678 commit 3a3ee82
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions diqu/utils/module.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

0 comments on commit 3a3ee82

Please sign in to comment.