I have the following directory structure in my python project
When I try to execute the test_market_rates.py file I get an Module not found error
ModuleNotFoundError: No module named 'lib'
But if I move the test_market_rates.py file to the main directory it will work without any errors
The following is how I have imported the module in test_market_rates.py file
from lib.utils import say_hello
print(say_hello())
Answer:
There might be related questions and answers.
For this particular problem, these are three possible solutions.
Assuming the following folder structure:
Solution 1: Run file from Root Folder
Run the script from
project_root
. I.e.:In Terminal (e.g. bash)
Solution 2: Create a proper package out of "lib"
Make a package out of
lib
. I.e. make it "pip installable", so that you can runpip install -e .
(local install). Then you will be able to call this file from both:project_root
&tests/test_market_rates
E.g.: https://betterscientificsoftware.github.io/python-for-hpc/tutorials/python-pypi-packaging/
In general, search for: "how to create a python package".
Solution 3: Add Relative Paths (Not Good Practice).
To the file
test_market_rates.py
add the following lines of code (before the lib import statement).You will be able to call this file from both:
project_root
&tests/test_market_rates
Reference: Find the current directory and file's directory