Chaos_Is_Harmony
Chaos_Is_Harmony

Reputation: 506

Trouble importing a module that itself imports another module in Python

Python version: 3.8.5

File structure

MainDir
   |
   | Utils --|
   |         | module1.py
   |         | module2.py
   |
   | Tests --|
             | test.py

module1.py imports module2.py test.py imports module1.py

When I run python Tests/test.py I get the following error:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    import Utils.module1
  File "<abspath>/MainDir/Utils/module1.py", line 16, in <module>
    import module2
ModuleNotFoundError: No module named 'module2'

I've tried the following:

1.) Python - Module Not Found

2.)

$export PYTHONPATH="$PWD"

3.) I've tried putting the test.py file at the same level as the Utils directory.

4.)

import sys
sys.path.append("../MainDir")

And several variations thereof.

They all failed.

The only thing that worked was just putting test.py in the Utils directory and running it from there. But I know there has to be a way to get it to work when it's in its own directory.

What am I missing?

UPDATE

The selected answer worked when trying to run test.py, but it broke when trying to run module1.py.

After some more research, running it with the -m flag and package syntax worked; in my case:

python -m Utils.module1

Hope this helps anyone else who runs into this problem.

Upvotes: 0

Views: 1331

Answers (2)

Alex SHP
Alex SHP

Reputation: 143

You may want to use relative imports.

So perhaps something like :

# in module1.py

import .module2

Relative imports mean that you are not trying to import from the __main__ file but from the current file (in your case module1.py).

Edit : Just realised I am stupid. This works for modules, not individual files. Please try again with from . import module2

Upvotes: 1

alparslan mimaroğlu
alparslan mimaroğlu

Reputation: 1480

if you structure your project like here you can use this. Also it is recommended to use relative import inside your packages

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

Upvotes: 0

Related Questions