Module Not found during import in Jupyter Notebook

Ryan picture Ryan · Mar 30, 2017 · Viewed 62.9k times · Source

I have the following package (and working directory):

WorkingDirectory--
                 |--MyPackage--
                 |            |--__init__.py
                 |            |--module1.py
                 |            |--module2.py
                 |
                 |--notebook.ipynb

In __init__.py I have:

import module1
import module2

If I try to import MyPackage into my notebook:

import MyPackage as mp 

I will get ModuleNotFoundError: No module named 'module1'. But import works fine if I execute the script outside a notebook: if I create test.py in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in __init__.py (import MyPackage.module1).

What's the reason for different import behavior?

I have confirmed the working directory of the notebook is WorkingDirectory.

---Update---------

Exact error is:

C:\Users\Me\Documents\Working Directory\MyPackage\__init__.py in <module>()
---> 17 import module1

ModuleNotFoundError: No module named 'module1'

My problem differs from the possible duplicate:

  1. The notebook was able to find the package, but only unable to load the module. This was inferred from substituting module1 with MyPackage.module1 worked well and suggests it may not be a problem related with PATH.

  2. I cded into WorkingDirectory and started the server there. The working directory should be the folder containing my package.

Answer

Louise Davies picture Louise Davies · Mar 30, 2017

I'm pretty sure this issue is related and the answer there will help you: https://stackoverflow.com/a/15622021/7458681

tl;dr the cwd of the notebook server is always the base path where you started the server, no matter was running import os os.getcwd() says. Use import sys sys.path.append("/path/to/your/module/folder").

I ran it with some dummy modules in the same structure as you had specified, and before modifying sys.path it wouldn't run and after it would