2

I have a file structure as follows:

└── project    
    ├── __init__.py
    ├── main.py
    └── package1
        ├── __init__.py
        ├── module1 
        └── subpackage
            ├── __init__.py
            └── module2.py

module2 contains a function called A, and module 1 imports module2 with the code:

from subpackage import module2

this works fine when running module1 directly, but when I then try to import module1 from main.py, I get an error. The code for the import statement in main.py is

from package1 import module1

this gives the error

  Traceback (most recent call last):
  File "C:\...\project\main.py", line 1, in <module>
    from package1 import module1
  File "C:\...\project\package1\module1.py", line 1, in <module>
    from subpackage import module2
ModuleNotFoundError: No module named 'subpackage'

I don't really understand what is happening here, I tried changing the current working directory with os.chdir() to package2 in module1, but this had no effect. Upon researching the problem, the only thing I could find that might relate to my problem was absolute vs relative imports, but changing the import statements didn't effect the error.

Nat
  • 23
  • 4

1 Answers1

1

In your module1.py file you need to provide full path (absolute) for the imported file. So if you want to run your code from the main.py file you need to change your import in the module1.py to:

from package2.subpackage import module2

or

import package2.subpackage.module2
Laszlowaty
  • 1,295
  • 2
  • 11
  • 19
  • Thanks, I came across this solution but thought it failed as it doesn't work when running 'module2.py' directly. – Nat Jan 13 '19 at 17:00