-1

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.

Newbielp
  • 431
  • 3
  • 16
  • 1
    Your script should not worry about modifying the system path. Rather, you should install modules in a directory already on the path (possibly via a virtual environment) or modify the path with the `PYTHONPATH` environment variable. – chepner Sep 19 '22 at 14:02
  • Where does your script (that wants to import `x`) actually live? – chepner Sep 19 '22 at 14:05
  • 2
    Please do not hack `sys.path` for this. It will only cause you more pain in the long run, and is in fact irrelevant to the second example. The second example is the correct approach - use relative imports. To fix it: the relative import must start at the folder which is your root package - `My_code_folder` - and thus we must use enough leading `.` to get there: `from ....lab_A.models_A.app_A1 import x`. Then, we must ensure that `My_code_folder` is a package on the module search path - **not** using sys.path, but by *starting the program properly*. – Karl Knechtel Sep 19 '22 at 14:16
  • @MattDMo as much as we desperately need a *good* canonical for these questions, the top several answers there are all horrible. – Karl Knechtel Sep 19 '22 at 14:19
  • @KarlKnechtel are *any* of them any good? Feel free to rearrange or add your own if you think another one would be better. These are just the ones I have bookmarked. – MattDMo Sep 19 '22 at 14:21
  • What finally has worked for me: ```import sys``` ```sys.path.insert(1, 'Users/User_ME/My_code_folder/lab_A/models_A/app_A1')``` ```import x``` If I tried ```from app_A1 import x``` or anything similar I would get an error ```ImportError: attempted relative import with no known parent package``` – Newbielp Sep 22 '22 at 08:06

1 Answers1

0

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
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18