pythonpython-3.8python-modulepython-packaging

ModuleNotFoundError when referencing folder in Python


I have a Python3 project arranged as follows:

C:\automation\framework\constants.py

C:\automation\tests\unit-tests\test_myunittest.py

In my unit test, I'm trying to call methods in framework folder, which has the required init.py file At the start of my unit test, I have the following imports:

import pytest
from framework import constants

When I call pytest, it throws the following error:

ModuleNotFoundError: No module named 'framework'

How do I fix this?


Solution

  • Most likely your directory (C:\automation\framework) is not on the python sys.path, so python cannot find the package framework.

    You could test this by checking the python path:

    from sys import path
    for p in path:
        print(p)
    

    To fix this you can add the path to framework manually by inserting it

    sys.path.append("C:\automation\framework")
    

    But this will only update sys.path for the current python session! So if you want to add framework permanently you could e.g. use a .pth-file in your python installation site-packages folder. Just create a new file like C:\PATH_TO_PYTHON\lib\site-packages\framework.pth with content:

    C:\automation\framework
    

    See more information on the python module search path here