path – Python cant find my module

path – Python cant find my module

Essentially, when you execute script.py directly, it doesnt know that its part of a submodule of src, nor does it know where a module named src might be. This is the case in either python 2 or 3.

As you know, Python finds modules based on the contents of sys.path. In order to import any module, it must either be located in a directory thats listed in sys.path, or, in the same directory as the script that youre running.

When you say python src/scripts/script.py, sys.path includes the Project/src/scripts/ (because thats where script.py is located), but not Project. Because Project isnt in the path, the modules in that directory (src) arent able to be imported.

To fix this:

Im assuming that your script.py is an entry point for your src module (for example, maybe its the main program). If thats true, then you could fix it by moving script.py up to the same level as src:

Project
├───.git
├───venv
|───script.py       <--- script.py moves up here
└───src
    ├───__init__.py
    └───mymodules
        ├───__init__.py
        ├───module1.py
        └───module2.py

This way, script.py can freely import anything in src, but nothing in src can import script.py.

If thats not the case, and script.py really is a part of src, you can use pythons -m argument to execute script.py as part of the src module like so:

$ python -m src.scripts.script

Because youve told python which module youre running (src), it will be in the path. So, script.py will be aware that its a submodule of src, and then will be able to import from src.

Be careful in this situation though – theres potential to create a circular import if something in src imports src.scripts.script.


As an alternative to both of these approaches, you can modify the sys.path directly in script.py:

import sys
sys.path.insert(0, /path/to/Project) # location of src 

While this works, its not usually my preference. It requires script.py to know exactly how your code is laid out, and may cause import confusion if another python program ever tries to import script.py.

Project
├───.git
├───venv
└───src
    ├───__init__.py
    ├───mymodules
    │   ├───__init__.py
    │   ├───module1.py
    │   └───module2.py
    └───scripts
        ├───__init__.py
        └───script.py

Alternatively you can import like the following in your script.py

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),../../))
import src.mymodules.module1

Now you can run script.py file from any location.

e.g :
python script.py
python /path to folder/script.py

path – Python cant find my module

If you face this problem when dealing with Pytest or coverage. Adding __init__.py file solve most of the cases.

Leave a Reply

Your email address will not be published. Required fields are marked *