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.

Revisions

  1. DiTo97 revised this gist Feb 16, 2024. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions !importing.py
    Original file line number Diff line number Diff line change
    @@ -36,12 +36,12 @@ def srcfile_import(modpath: str, modname: str) -> "types.ModuleType":

    module = importlib.util.module_from_spec(spec)

    # It adds the module to the global scope
    sys.modules[modname] = module

    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)

  2. DiTo97 created this gist Feb 16, 2024.
    48 changes: 48 additions & 0 deletions !importing.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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)

    # It adds the module to the global scope
    sys.modules[modname] = module

    if spec.loader is None:
    message = f"No spec loader for module at {modpath}"
    raise ImportError(message)

    spec.loader.exec_module(module)

    return module