1

This is the folder structure of my project in python (version 3.9.13):

src
    modules
        __init__.py
        fileA.py
    main.py    

tests
    __init__.py
    test_main.py
    test_fileA.py

When I run main.py I get the error "ModuleNotFoundError: no module named src" in line 4 (in main.py) which contains the following import:

from src.modules.fileA import classOfFileA

How can i resolve it?

I tried to remove "src" from line 4 but this way I have some problems in tests. In fact in test_main.py the following import fails:

from src.main import *

with the error: ModuleNotFoundError: No module named 'modules'

luke_mcp
  • 11
  • 3
  • Does this answer your question? https://stackoverflow.com/questions/51049663/python3-6-error-modulenotfounderror-no-module-named-src – MrDiamond Dec 17 '22 at 19:23

1 Answers1

0

You said "When I run main.py ..."

What you want is "When I run src/main.py"

$ python src/main.py

Take a look at $ python -m site output. Your PYTHONPATH env var should mention . dot, the current directory, and the site output should mention the top level directory of your project.

Invoke your code from the project's top level, and the . dot in the env var will do the rest for you.


Similarly,

$ python -m unittest tests/test_*.py

should work fine.

(Or perhaps you prefer -m unittest test/test_main.py, which is same as -m unittest test.test_main.)

J_H
  • 17,926
  • 4
  • 24
  • 44
  • your answer was very helpful, but i had a question: every time i work on a project on a new folder so is it necessary to set the PYTHONPATH on that folder? – luke_mcp Dec 19 '22 at 13:03
  • The unix PATH env var sometimes contains `.` dot, denoting "current directory", so that `$ which myscript.sh` might obtain it from wherever you've `cd`'d to. Similarly, PYTHONPATH typically contains `.` dot, so that `import mymodule` succeeds. You don't _have_ to include dot, if you prefer long hardcoded pathnames. When you switch to new folder, `.` dot lets you use that folder. On a slightly separate topic, you probably want a new `poetry` or `conda` virt env for each project, in which case you would adjust path each time you switch projects, e.g. with `$ conda activate myproject`. – J_H Dec 19 '22 at 16:49