Manipulating sys.path in a Helper Module in the Current Directory§

Instead of manipulating the path in each notebook (like shown in this notebook), we can create a helper module in the current directory which does the path manipulations. For the current notebook, there is a helper module in the same directory: mymodule.py. This helper module does some obscure manipulations that make it look like it’s the module from ../module-subdirectory/mymodule.py.

[1]:
import mymodule
[2]:
mymodule.hello()
Hello, world!

Admittedly, the code looks quite scary:

[3]:
%cat mymodule.py
# Import a module with the same name from a different directory.

import importlib
import os
import sys

sys.path.insert(0, os.path.abspath('../module-subdirectory'))

if not hasattr(importlib, 'reload'):
    importlib.reload = reload  # for Python 2 compatibility

# Temporarily hijack __file__ to avoid adding names at module scope;
# __file__ will be overwritten again during the reload() call.
__file__ = {'sys': sys, 'importlib': importlib}

del importlib
del os
del sys

__file__['importlib'].reload(__file__['sys'].modules[__name__])