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
.