Issue
I have the following file structure
Working Directory
|
|-- Package
| |-- __init__.py
| |-- FirstModule.py
| |-- SecondModule.py
| |-- TestingFile.ipynb
|
|-- WorkingFile.ipynb
FirstModule.py
def func(n):
return n+1
SecondModule.py
import FirstModule
def func2(n):
value = FirstModule.func(n)
return (n, value)
When I import either module into TestFile.ipynb
they work perfectly fine as shown here:
TestingFile.ipnyb
import FirstModule # Works Fine
import SecondModule # Works Fine
However, If I am in WorkingFile.ipynb
and try to import SecondModule
I receive a ModuleNotFoundError
. More Specifically:
WorkingFile.ipynb
from Package import SecondModule as sm
from Package import FirstModule as fm
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-14-8a837a311e6c> in <module>
2 import numpy as np
3
----> 4 from Package import SecondModule as sm
5 from Package import FirstModule as fm
~\Documents\Jupyter Notebooks\Working Directory\Package\SecondModule.py in <module>
26 from datetime import datetime
27
---> 28 import FirstModule as fm
29
30 # Constants
ModuleNotFoundError: No module named 'FirstModule'
Could there be something that I am forgetting that is needed for modules to work together outside of the package that they are contained inside of?
Solution
The issue is the import statement in SecondModule.py
.
I was able to reproduce the error using your example and when I change the import statement from
import FirstModule.py
to
from Package import FirstModule
It all works fine. You should not use the filename i.e. drop the .py from the import statement
You should use the package name explicitly when importing modules or alternatively use relative imports, i.e.
from . import FirstModule
or in case you only want specific objects/functions
from .FirstModule import some_function
Answered By - Omri Bahat Treidel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.