2

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

3
  • You can import locally from a script (i.e. when you run main.py directly) but not from a module. You need to change main.py to an absolute import as well: from root.folder1 import * Commented Feb 22, 2019 at 17:02
  • (when you from root.folder1.main import ... then main is treated as a module) Commented Feb 22, 2019 at 17:10
  • Your question seems similar to this one: stackoverflow.com/questions/54793765/… Commented Feb 22, 2019 at 22:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.