0

I have this package I designed which have the following structure,

General/
    __init__.py
    Vector/
        __init__.py
        module_1.py
    module_A.py

In module_A there is a just a function prints a string.

In module_1 there is,

from ...General import module_A
module_A.function()

Then I create a separate python file First.py which only has the line import General.Vector.module_1.

I put this file in to the parent directory of General and locate cmd to the parent directory and run python First.py

Then I get the error ValueError: attempted relative import beyond top-level package

But if I change module_1 to

from .. import module_A
module_A.function()

Then this works.

I searched for a solution and from this post, I got a good understanding about relative imports. Then it was pointed out to me that if I add my package to sys.path then python First.py would work regardless of where the First.py is located.

So I tried to add my package to sys.path as this post suggests.

I changed my First.py to

import sys
sys.path.insert(0,'/path/to/General')
import General.Vector.module_1

But that didn't work.

1 I like to know the reason for this two different behaviours for module_1's changes.

2 I like to know how to add my package to sys.path.

Algo
  • 35
  • 9
  • If you're importing `General.Vector.module_1` then `General` is the top-level package. If you do `from ...General` then it steps *outside* of that package (which is not possible), just to reenter it. It's like if your `pwd` is `/path/to/foo/bar` and instead of `cd ../baz` you do `cd ../../foo/baz`; the `../foo` part is redundant here. Nevertheless it works because the file system is seen as a whole. However Python only knows the structure of your package and that is limited by `General` (i.e. it doesn't know what exists beyond `General`). – a_guest Apr 29 '20 at 12:26
  • You can add your package to `sys.path` but you should add `"/path/to"` instead of `"path/to/General"` since it attempts to locate the package `General` *inside* that path. – a_guest Apr 29 '20 at 12:27
  • @a_guest Actually it worked with the `sys.path` – Algo Apr 29 '20 at 12:35
  • @a_guest so we are not allowed step out of the top level package at anytime. is it correct? – Algo Apr 29 '20 at 12:36
  • That's what the error says, yes. Packages do not necessarily have to live on the file system, so from the perspective of the Python import machinery there is really nothing beyond the top-level package. – a_guest Apr 29 '20 at 13:02
  • @a_guest now I get it thank you very much. – Algo Apr 29 '20 at 13:48
  • 1
    @napuzba It also helped me thank you! – Algo Apr 30 '20 at 19:28

0 Answers0