I have a project with this directory structure
I want to import a def from functions.py
from notebook01.ipynb
.
I followed the documentation of relative path import here and studied the answers in this stack overflow post.
I tried to write from .Modules.functions import fibonacci
, (With one dot before the Modules
folder) I got the following error.
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-2-be5f30231faa> in <module>
----> 1 from .Modules.functions import fibonacci
ModuleNotFoundError: No module named '__main__.Modules'; '__main__' is not a package
And I tried to add two or three dots before the Modules
folder from ..Modules.functions import fibonacci
then I got the error
ValueError Traceback (most recent call last)
<ipython-input-3-8d1656059c1f> in <module>
----> 1 from ..Modules.functions import fibonacci
ValueError: attempted relative import beyond top-level package
I have added the __init__.py
files at each level of the directory structure as suggested by the documentations]2 as you see, but no luck at all!
What am I doing wrong?
I'll be honest: relative import could be hell. That's why Python 3 does absolute imports by default (https://docs.python.org/2.5/whatsnew/pep-328.html).
If you use Python 3 - make all your packages absolute.
If you still use Python 2 you can switch default behavior by adding the following line at the top:
from __future__ import absolute_import