0

I'm trying to import a file from another directory but it's not working.

App
|___init__.py
|_notebooks
| |__init__.py
| |_test.py
|_src
| |___init__.py
| |_loss.py

I want to import loss in test.py. I have tried

from src import loss --> which is giving me no module named src error

from .src import loss and from ..src import loss --> gives attempted relative import with no known parent package

sys.path.insert(0, '../src/')
import loss

is working but I want to do it without using sys. so that there won't be any headache in the production and I believe its possible. i have gone through this thread but none of the solutions seems to be working.

Ashwath Shetty
  • 106
  • 1
  • 10
  • You need to understand how python discoveres modules. The solution is to make your package installable, then to install it. Then it doesn't matter what your working directory is, it will be discovered on import (usually by being put into site-packages) – juanpa.arrivillaga Sep 29 '21 at 04:33

1 Answers1

0

You need to execute test.py in a way that makes Python aware of the src folder. That is, python notebooks/test.py won't work because Python will take the location of your script (i.e. the notebooks folder) as starting point for imports. This explains the attempted relative import with no known parent package error.

To fix it, call it with its package structure included: python -m notebooks.test, you can then use from src import loss.

Jan Wilamowski
  • 3,308
  • 2
  • 10
  • 23