Last active
September 2, 2022 01:06
-
-
Save gh640/903b47c38129d1dec67017b350cce20d to your computer and use it in GitHub Desktop.
Python: importing a Python module without `.py` extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from importlib.machinery import SourceFileLoader | |
from importlib.util import module_from_spec, spec_from_file_location | |
from pathlib import Path | |
def import_path(path: Path): | |
module_name = path.stem.replace('-', '_') | |
loader = SourceFileLoader(module_name, str(path)) | |
spec = spec_from_file_location(module_name, path, loader=loader) | |
module = module_from_spec(spec) | |
spec.loader.exec_module(module) | |
return module | |
if __name__ == '__main__': | |
mymodule_path = Path(__file__).parent / 'mymodule' | |
mymodule = import_path(mymodule_path) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print(f'{__name__} is loaded.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result output:
python import_path.py # => mymodule is loaded.
See: