Reputation: 51
For a new structure in the python 3.10 project I had to separate diffrent modules from each other and moved them in diffrent folders on the same layer. The folder stucture looks kinda similar to this:
Root
-- main.py
-- __init__.py
-- folder1
----- __init__.py
----- a.py
-- folder2
----- __init__.py
----- b.py
I defined a function in a.py like this:
# /root/folder1/a.py
def testFunction(text):
print(text)
In the Root init file i referenced this function like so:
# /root/__init__.py
from .folder1.a import testFunction as testFunction
So I tried to use the function in module folder1/a.py in module folder2/b.py:
# /root/folder2/b.py
from .. import testFunction
text = 'hello World'
testFunction(text)
I searched on GitHub for a bigger python projects and found the solution on top for module references but it didn't worked for me. I tried following solutions which also didn't worked:
So my problem is, that this Error shows up:
ImportError: attempted relative import with no known parent package
thank you verry much for every hint or solution :-)
Upvotes: 4
Views: 419
Reputation: 51
I found out, that I could work with sys.path.append & os.path.abspath. So the solution is like this:
directory stucture:
Root
-- main.py
-- __init__.py
-- folder1
----- __init__.py
----- a.py
-- folder2
----- __init__.py
----- b.py
To use testFunction from folder1/a.py in folder2/b.py the code in b.py should be like this:
import sys
import os
sys.path.append(os.path.abspath('../Root/folder1'))
from a import testFunction
Upvotes: 1