Diego
Diego

Reputation: 36146

python import local module from another module

I have the following structure:

root/
    folder1/
        main.py
        secondary.py
    folder2/
        test.py

the main.py code always runs from the root folder, so on the main.py I have an

from folder1.secondary import * 

so I can use its functions on main.py - that works fine

on tests.py, I do:

from root.folder1.main import myfunction 

(that is the only function I need to test) but it fails saying "ModuleNotFoundError: No module named 'folder1.secondary'

root is on sys.path

I dont understand why importing main.py directly works but importing from another folder doesn't. How can I solve this problem?

Thanks

Upvotes: 2

Views: 3303

Answers (1)

Aakash Sethi
Aakash Sethi

Reputation: 76

You will have to have a file called __init__.py in each directory so the Python interpreters treats that directory as a module it can import things from. The file can be empty but it has to be named like that.

Your new directory structure would look like:

root/
    __init__.py
    folder1/
        __init__.py
        main.py
        secondary.py
    folder2/
        __init__.py
        test.py

Then you can import your main.py in the test.py by doing from root.folder1.main import myfunction.

Upvotes: 1

Related Questions