19 lines · python
1import importlib.util2import os3import sys4 5 6def load_module(name, path, mod_file="__init__.py"):7 # The module is either defined by a directory, in which case we search for8 # `path/name/__init__.py`, or it is a single file at `path/mod_file`.9 mod_path = (10 os.path.join(path, name, mod_file)11 if mod_file == "__init__.py"12 else os.path.join(path, mod_file)13 )14 spec = importlib.util.spec_from_file_location(name, mod_path)15 module = importlib.util.module_from_spec(spec)16 sys.modules[name] = module17 spec.loader.exec_module(module)18 return module19