How do you dynamically import a Python module from its full file path? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you dynamically import a Python module from its full file path?

message-square
0

Use importlib.util.spec_from_file_location(module_name, file_path) paired with importlib.util.module_from_spec(spec) and spec.loader.exec_module(module)—which loads any .py file directly from an arbitrary filesystem path without polluting sys.path or requiring the parent folder to be a package.

Basic Example

import importlib.util
from pathlib import Path
import sys

def import_from_path(module_name: str, file_path: str | Path):
    path = Path(file_path).resolve()

    # 1. Create a ModuleSpec pointing directly to the target .py file
    spec = importlib.util.spec_from_file_location(module_name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load module '{module_name}' from {path}")

    # 2. Instantiate the empty module object and register it in sys.modules
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module

    # 3. Execute the module's top-level code to populate its namespace
    spec.loader.exec_module(module)
    return module


# Example usage:
plugin = import_from_path("my_custom_plugin", "/opt/plugins/transform.py")
plugin.run()

Key Details & Edge Cases

  • Always register sys.modules[module_name] = module before calling spec.loader.exec_module(module):
    • If the loaded file uses @dataclass, typing.get_type_hints(), namedtuple, pickle, or self-referential imports during module execution, Python looks up sys.modules[cls.__module__]. Skipping sys.modules registration causes AttributeError: 'NoneType' object has no attribute '__dict__' on @dataclass classes in Python 3.10+.
    • Clean up sys.modules.pop(module_name, None) in an except Exception: block if exec_module() fails so a half-initialized broken module does not remain cached.
  • Unique module_name collisions when loading multiple files with the same filename:
    • If you load two different plugins both named plugin.py (e.g., /plugins/a/plugin.py and /plugins/b/plugin.py) under the same module_name="plugin", the second registration overwrites the first in sys.modules. Give each file a distinct logical name such as "plugins.a.plugin" and "plugins.b.plugin".
  • Relative imports inside the dynamically loaded file (from . import helper):
    • A standalone .py file loaded via spec_from_file_location() has __package__ == "" unless its parent directory is also loaded as a package (submodule_search_locations). If the target file contains relative imports (from .utils import x), load its parent __init__.py first or use dotted package names ("my_pkg.sub") with submodule_search_locations=[str(pkg_dir)].
  • Bytecode .pyc files work too:
    • spec_from_file_location() automatically selects SourcelessFileLoader when passed a .pyc path and SourceFileLoader when passed a .py path.
  • Avoid deprecated imp.load_source() and exec(open(path).read()):
    • The imp module was removed in Python 3.12, and raw exec() fails to set __file__, __name__, __spec__, or __loader__ properly—breaking relative resource paths (Path(__file__).parent) and traceback filenames inside the loaded file.

Comparison of Dynamic File-Path Import Approaches in Python

Approach Python Version Sets __file__, __spec__, & sys.modules? Pollutes Global sys.path? Best Used When
importlib.util.spec_from_file_location (Recommended) Python 3.5+ (current standard) Yes No Loading plugins, user scripts, or config .py files from exact filesystem paths.
Temporary sys.path + importlib.import_module Python 3.1+ Yes Temporarily (must clean up in finally:) Loading a module whose own internal absolute imports depend on sibling files in its folder.
runpy.run_path(path) Python 2.7+ / 3.x Sets __file__ (returns globals dict, not a module) No Executing a standalone script once and inspecting its returned namespace dictionary.
imp.load_source() (Removed) Removed in Python 3.12 Yes No Legacy Python 2 / early Python 3 codebases only (replace with importlib.util).