0

I have the following folder layout:

enter image description here

The files have the following contents:

library.py

def add(x: int, y: int) -> int:
    return x + y

test.py

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))


from src.code.library import add


print(add("as", 2))

Now, when I run the following command from inside test/:

  • python test.py

I get the following error:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    from src.code.library import add
ModuleNotFoundError: No module named 'src'

Can someone please help me out? I am using Python 3.8 so apparently do not need the __init__.py files that a lot of the answers I looked at previously.

Any guidance would be much appreciated. I read the canonical answer here:

Relative imports for the billionth time

But did not really understand how it works for Python 3.8. The type error in the code is intentional.

zigzagzoom
  • 41
  • 3
  • you definitely need the `__init__.py` files (to create packages) and you don't need to use `sys.path` (or at least `__init__.py` files make is so much easier) – Matiiss Aug 18 '21 at 12:56
  • Thanks @Matiiss, would you know how I could solve my problem? I used added an init file in my `src` directory but it has not helped. – zigzagzoom Aug 18 '21 at 13:01
  • `code` directory also should be a package and so should be `test` or at least so I understand – Matiiss Aug 18 '21 at 13:05

0 Answers0