Skip to content

Instantly share code, notes, and snippets.

Last active September 2, 2022 01:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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)
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