Skip to content

Instantly share code, notes, and snippets.

@MondeSinxi
Created January 23, 2024 20:09
Show Gist options
  • Save MondeSinxi/2d81915e214d0fea55a00e708909fe57 to your computer and use it in GitHub Desktop.
Save MondeSinxi/2d81915e214d0fea55a00e708909fe57 to your computer and use it in GitHub Desktop.
Dynamically load modules
import importlib.machinery
import importlib.util
import sys
def load_module(mod_name: str, filepath: str) -> None:
"""
Dynamically loads a Python module from the given file path and adds it to sys.modules.
Args:
mod_name (str): The name to be used for the loaded module.
filepath (str): The file path to the Python module.
Returns:
None
"""
# Create a loader for the given module name and file path
loader = importlib.machinery.SourceFileLoader(mod_name, filepath)
# Create a module specification from the loader
spec = importlib.util.spec_from_loader(mod_name, loader)
# Create a new module object from the specification
new_module = importlib.util.module_from_spec(spec)
# Add the new module to sys.modules with the specified module name
sys.modules[mod_name] = new_module
# Execute the module code within the new module object
loader.exec_module(new_module)
return new_module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment