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:
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
.
I cded into WorkingDirectory
and started the server there. The working directory should be the folder containing my package.
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With