0

I have a project with this directory structure PythonProjectDirectoryStructure

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?

Mohammad ElNesr
  • 2,477
  • 4
  • 27
  • 44
  • https://stackoverflow.com/questions/51046660/how-to-resolve-valueerror-attempted-relative-import-beyond-top-level-package – deets Jan 31 '19 at 08:26
  • 1
    Try `sys.path.append(os.path.abspath(".."))`. Then `import Modules.functions as functions`. – a_guest Jan 31 '19 at 08:27
  • Thanks for all replies, but I wonder if I should add the absolute path to the system! and what if I shared the problems with some friends, should everyone change the code to include the absolute path? – Mohammad ElNesr Jan 31 '19 at 08:35
  • Also, what will happen if the user's prevailages are limited, and can't change the path? (I use Windows) – Mohammad ElNesr Jan 31 '19 at 08:36
  • I found a good workaround **WITHOUT adding to the system path** [here in this post](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) – Mohammad ElNesr Jan 31 '19 at 09:00

1 Answers1

0

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
Szczad
  • 787
  • 6
  • 12