Importing files from src folder into test folder

Viewed 658

Trying to import files from a sibling directories. the project tree looks like:

my_project
    __init__.py
    src
        __init__.py
        someFile.py
        
    test
        __init__.py
        myTest.py
        

i'm trying to import a class from someFile.py into myTest.py in other answers i found 2 methods:

1 - importing directly if i have __ init__.py in my directory making it a package

from src.somefile import myClass

ModuleNotFoundError: No module named 'src'

2- messing with sys os :

import sys
import os
sys.path.append(os.path.abspath('../src'))
from src.someFile import myClass

ModuleNotFoundError: No module named 'src'

I am not sure what am I doing wrong. all answers on stackoverflow are basically those 2 methods. a 3rd way i tried was

from ..src.someFile import myClass

but the same error persist. As I am new to python developement, can anyone tell me what am i doing wrong?

1 Answers

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
Related