Both absolute and relative imports failing in Python

Viewed 55

I have a problem where both absolute and relative imports are failing in a non-obvious manner. I have the following directory structure:

package1
    __init__.py
    src
        test1.py
        lib
            test2.py
            __init__.py
         __init__.py

Test1.py has the following code:

import os
print(f'CWD in test12.py is : {os.getcwd()}')
from src.lib import test2

Test2.py has the following code:

import os
print(f'CWD in test2.py is : {os.getcwd()}')
from package1.src import test1

If I am positioned in package1 and I run the following command, I get the result:

PS C:\Users\jgoss\Personal\package1> python src/test1.py
CWD in test2.py is : C:\Users\jgoss\Personal\package1
Traceback (most recent call last):
  File "C:\Users\jgoss\Personal\package1\src\test1.py", line 3, in <module>
    from src.lib import test2
ModuleNotFoundError: No module named 'src'

which does not make sense to me as src is a package, not a module.

If I change test1.py and test2.py to use relative imports like this:

Test1.py

import os
print(f'CWD in test12.py is : {os.getcwd()}')
from ..lib import test2
test2.py

PS C:\Users\jgoss\Personal\Infrastructure> python src/test1.py
CWD in test12.py is : C:\Users\jgoss\Personal\package1
Traceback (most recent call last):
  File "C:\Users\jgoss\Personal\package1\src\test1.py", line 3, in <module>
    from ..lib import test2
ImportError: attempted relative import with no known parent package

which I cannot interpret since package1 is a package. Can anyone see what I am doing wrong?

The only unusual thing that I can see is that there is a mutual dependency between test1.py and test2.py since each one imports the other.

0 Answers
Related