You need to add that directory to the path:
import sys
sys.path.append('../src')
Maybe put this into a module if you are using it a lot.
There are three ways to do what you want.
root_dir
├── my_module
│ ├── __init__.py
│ ├── main_file.py
│ ├── file1.py
│ ├── file2.py
└── tests
├── __init__.py
└── file1_test.py
All files in shoud import likemy_module
from my_module.file1 import some_function
Then you don't need to do any hacks
src and assuming statements likefrom src.file1 import some_function
are not what you want you need to modify your tests like
import os
import sys
sys.path.insert(0, os.path.abspath('src')
PYTHONPATH=path/to/src pytest
if anyone is having the same error i found a solution: you need to update your python path so it has both the parent directory and the sibling one.(like shown below)
import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../src'))
from src.someFile import myClass
The correct format is as follows:
repo
├── .vscode
│ ├── settings.json
├── src
│ ├── classA.py
│ └── classB.py
└── tests
├── __init__.py (empty file)
├── classA_test.py
└── classB_test.py
classA_test.py
import unittest
from src.classA import fetchData
class classA(unittest.TestCase):
def testStuff(self):
..testStuff..
You can use this code found here:
# test.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/utils/')
import utils
Is the virtual environment where you installed 'src' same, where you are trying this.
Pls. run the
pip list
in that virtual environment to check if 'src' is installed.
Also, pls. check the import statement in the python interpreter of your virtual env.
If scripts are executed from inside a package, then various hacks need to be employed to get the imports to work properly. Probably the most common of these is to manipulate :sys.path
import sys, os
sys.path.insert(0,
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src import stringbuilder
del sys.path[0]
There is no way to achieve this using normal import statements.
A generally better solution is to simply avoid running scripts inside packages altogether. Instead, put all scripts outside the package in a containing directory. Given that the directory of the currently running script is automatically added to the start of , this will guarantee that the package can be always be directly imported, no matter where the script is executed from.sys.path
So the directory structure might look something like this:
project /
package /
__init__.py
src /
__init__.py
stringbuilder.py
tests /
__init__.py
stringbuilder_test.py
main.py
test.py
The script can then import its tests like this:test.py
from package.tests import stringbuilder_test
And can import the stringbuilder_test.py modules like this:src
from package.src import stringbuilder