3

From Python relative imports for the billionth time:

  • For a from .. import to work, the module's name must have at least as many dots as there are in the import statement.
  • ... if you run the interpreter interactively ... the name of that interactive session is __main__
  • Thus you cannot do relative imports directly from an interactive session

I like to use interactive Jupyter Notebook sessions to explore data and test modules before writing production code. To make things clear and accessible to teammates, I like to place the notebooks in an interactive package located alongside the packages and modules I am testing.

package/

    __init__.py

    subpackage1/

        __init__.py

        moduleX.py

        moduleY.py

        moduleZ.py

    subpackage2/

        __init__.py

        moduleZ.py

    interactive/
        __init__.py
        my_notebook.ipynb

During an interactive session in interactive.my_notebook.ipynb, how would you import other modules like subpackage1.moduleX and subpackage2.moduleZ?

Community
  • 1
  • 1
andrew
  • 3,929
  • 1
  • 25
  • 38

1 Answers1

3

The solution I currently use is to append the parent package to sys.path.

import sys
sys.path.append("/Users/.../package/")

import subpackage1.moduleX
import subpackage2.moduleZ
andrew
  • 3,929
  • 1
  • 25
  • 38
  • 1
    I think it would make more sense to add `package`'s parent directory to `sys.path`. This way you can always do `from package.subpackageN import moduleZ` – theorifice Jul 20 '16 at 19:21