Recipe 1
import importlib.machinery
import importlib.util
import sys
from pathlib import Path
finder = importlib.machinery.PathFinder()
spec = finder.find_spec(
'directoryManager',
[str(Path(__file__).resolve().parent.parent / 'sub1')]
)
# or finder.find_spec('directoryManager', ['../sub1']) if cwd is sub2
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
This recipe doesn't need the full path of the file. Thus it is useful for importing extensions (they have suffixes like .cpython-38-aarch64-linux-gnu.so
).
Recipe 2
import importlib.util
import sys
from pathlib import Path
spec = finder.spec_from_file_location(
'directoryManager',
str(Path(__file__).resolve().parent.parent / 'sub1' / 'directoryManager.py')
)
# or finder.spec_from_file_location('directoryManager, '../sub1/directoryManager.py') if cwd is sub2
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
This recipe is more straightforward and simple.
Adapted from https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
Reference
https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported
(importlib.util.find_spec
internally use PathFinder.find_spec
)