Skip to content

Instantly share code, notes, and snippets.

@DiTo97
Last active February 16, 2024 02:28
Show Gist options
  • Save DiTo97/46f4b733396b8d7a8f1d4d22db902cfc to your computer and use it in GitHub Desktop.
Save DiTo97/46f4b733396b8d7a8f1d4d22db902cfc to your computer and use it in GitHub Desktop.
A minimal collection of import utility functions
import sys
import typing
if typing.TYPE_CHECKING:
import types
def srcfile_import(modpath: str, modname: str) -> "types.ModuleType":
"""It imports a python module from its srcfile
Parameters
----------
modpath
The srcfile absolute path
modname
The module name in the scope
Returns
-------
The imported module
Raises
------
ImportError
If the module cannot be imported from the srcfile
"""
import importlib.util
#
spec = importlib.util.spec_from_file_location(modname, modpath)
if spec is None:
message = f"No spec for module at {modpath}"
raise ImportError(message)
module = importlib.util.module_from_spec(spec)
if spec.loader is None:
message = f"No spec loader for module at {modpath}"
raise ImportError(message)
# It adds the module to the global scope
sys.modules[modname] = module
spec.loader.exec_module(module)
return module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment