Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active September 2, 2022 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gh640/903b47c38129d1dec67017b350cce20d to your computer and use it in GitHub Desktop.
Save gh640/903b47c38129d1dec67017b350cce20d to your computer and use it in GitHub Desktop.
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