0

I know this has been asked before but I still can't wrap my head around how this works. I'm trying to do a pretty simple thing which should intuitively work but doesn't, please help me what I'm doing wrong. I have a folder structure like this:

src/
    foo/
       __init__.py
       foo.py
    bar/
       __init__.py
       bar.py
       xyz.py

I'm trying to import the XYZ class in xyz.py from within foo.py. If I write

from bar.xyz import XYZ

I get

ModuleNotFoundError: No module named 'bar'

But if I write

from ..bar.xyz import XYZ

I get

ImportError: attempted relative import with no known parent package

I also tried doing

from src.bar.xyz import XYZ

But again I get

ModuleNotFoundError: No module named 'src'

I try adding __init__.py in src/ but that also results in the same error. I know I can call sys.add or something and the parent path before importing but that really seems like an hack which I don't want to do. What am I missing here?

Amol Borkar
  • 2,321
  • 7
  • 32
  • 63
  • Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Ake Jul 08 '23 at 07:32
  • I had almost the exact same problem with one of my projects, and for me the solution was to make the entire project "installable" and use relative imports for everything, but I did that also because it was large and harder to solve the issue without doing so. In your case, your import will simply work if you run the foo as a module like this: `python -m foo.foo` – Ake Jul 08 '23 at 07:48

0 Answers0