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] = modulebefore callingspec.loader.exec_module(module):- If the loaded file uses
,typing.get_type_hints(),namedtuple,pickle, or self-referential imports during module execution, Python looks upsys.modules[cls.__module__]. Skippingsys.modulesregistration causesAttributeError: 'NoneType' object has no attribute '__dict__'onclasses in Python 3.10+. - Clean up
sys.modules.pop(module_name, None)in anexcept Exception:block ifexec_module()fails so a half-initialized broken module does not remain cached.
- If the loaded file uses
- Unique
module_namecollisions when loading multiple files with the same filename:- If you load two different plugins both named
plugin.py(e.g.,/plugins/a/plugin.pyand/plugins/b/plugin.py) under the samemodule_name="plugin", the second registration overwrites the first insys.modules. Give each file a distinct logical name such as"plugins.a.plugin"and"plugins.b.plugin".
- If you load two different plugins both named
- Relative imports inside the dynamically loaded file (
from . import helper):- A standalone
.pyfile loaded viaspec_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__.pyfirst or use dotted package names ("my_pkg.sub") withsubmodule_search_locations=[str(pkg_dir)].
- A standalone
- Bytecode
.pycfiles work too:spec_from_file_location()automatically selectsSourcelessFileLoaderwhen passed a.pycpath andSourceFileLoaderwhen passed a.pypath.
- Avoid deprecated
imp.load_source()andexec(open(path).read()):- The
impmodule was removed in Python 3.12, and rawexec()fails to set__file__,__name__,__spec__, or__loader__properly—breaking relative resource paths (Path(__file__).parent) and traceback filenames inside the loaded file.
- The
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). |
You must log in or register to comment.
