Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active Sep 2, 2022
Embed
What would you like to do?
Python: importing a Python module without `.py` extension
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)
print(f'{__name__} is loaded.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment