Import a class in a module that lives in different directory

Viewed 40

I need some help as I try to import a class which lives in x.py into y.py.

Both app_A1 and app_B1 contain an empty __init__.py and so does the My_code_folder.

enter image description here

I have tried a few ways to import it such as:

import sys

# first
sys.path.append('../')
from lab_A.models_A.app_A1 import x

# second
sys.path.append('../')
from .lab_A.models_A.app_A1 import x

# third
sys.path.append('../')
from Users.User_ME.My_code_folder.lab_A.models_A.app_A1 import x

# fourth
sys.path.insert(1, 'Users/User_ME/My_code_folder/lab_A/models_A/app_A1')
from app_A1 import x

and I get ModuleNotFoundError or ImportError: attempted relative import with no known parent package.

What am I doing wrong?

PS: I work in Spyder if it is a useful piece of information.

1 Answers

You can insert the files to you python path, but this depends on where you run the file (i.e. cd first in the directory or not).

import pathlib
this_path = pathlib.Path(__file__).parent # folder of y.py
import sys
sys.path.insert(0, this_path/../../../lab_A/models_A/app_A1)
import x.py
Related