0

I have searched and not found a good answer. I have something very simple:

src/image.py
test/test.py

test.py is intended to test image.py so it needs to import it. It would seem logical that one would simply do

import ../src/image

or

import ..src.image

or

from ..src import image

But none of those work. When I search the forum I get lots of complicated answers, some of which require python to be started in a special mode to work. But why? It is just a file. The fact that it happens to be located in another directory, even one whose Linux path begins with .. should be irrelevant?

Please help me understand, and if there is a simpler way to do this, please help me find it ;-)

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
amjjam
  • 1
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Gino Mempin May 25 '23 at 03:34
  • The key is adding the containing directory to your `sys.path`, based on the script's location in `__file__`. Once `src` is in the path, you can `import image`. – Tim Roberts May 25 '23 at 03:36
  • The latter two attempts would work if only you'd run Python from the parent directory of `test` and `src`. – blhsing May 25 '23 at 03:38
  • That's just how the Python import system (unfortunately) works. It is not about "*It is just a file*" and whether it is following path convention for ".." – Gino Mempin May 25 '23 at 04:05
  • Thanks a lot for comments so far. The "billionth time" is interesting reading, and confusing reading. I am still chewing on it. It does seem to clarify that the path in an import doesn't refer to a path in the directory tree. It might do so by coincidence. Beyond that I don't yet understand it. As for using sys.path, I am doing that as a stop-gap, but the problem with it is that I can't specify where the file is. Instead I have to hope that it is the first one that python finds when it does the import (it was in this case). – amjjam May 25 '23 at 04:23

0 Answers0