0

I know there are many similar questions out there already, but none of the answers did really work for me, so please read my question first (and tell me where I went wrong with the other solutions) before marking this as duplicate.

My project structure looks like this:

Project/
|-- src/
    |-- project/
        |-- a.py
        |-- b.py
        |-- tests/
            |--c.py

I don't know much about how to strucure python projects/how packages etc. work exactly. I want to import a in my c module.

I tried things like

from project.a import xyz
from ..a import xyz

I also added __init__.py files to both the project and the tests directory.

But still I always get ModuleNotFoundError: No module named 'project'

Then I tried adding the project path to my sys.path before importing a, but still I get the same error message.

What am I doing wrong?

Jannik
  • 399
  • 2
  • 5
  • 22

1 Answers1

1

Adding __init__.py, and adding the project path with sys.path, and import a should work. But I would recommend to try the following in your c.py:

import sys
from pathlib import Path

filepath = Path(__file__)
filepath = filepath.parent
sys.path.insert(0, str(filepath))
import a

Why? This is a generic solution that will work as long as the relative path from c to a stays the same.

don-joe
  • 600
  • 1
  • 4
  • 12
  • I added `__init__.py` files in both dirs, but still it's not working. I get the same error. – Jannik Feb 04 '21 at 11:17
  • What exactly is the import statement? Does just "import a" work? – don-joe Feb 04 '21 at 13:38
  • It didn't, but when I replaced `sys.path.insert` with `sys.path.append` somehow it worked, however I'm pretty sure that I already tried exactly that before... Maybe I did something else wrong that time, I don't know – Jannik Feb 04 '21 at 13:51