0

I have the following project structure:

├── my_app
    ├── __init__.py
    ├── my_pkg
    │   ├── __init__.py
    │   ├── utils.py
    │   ├── app.py
    ├── other_pkg...
    │   ├── __init__.py
    │   ├── ...
    ├── ...

I want in the my_app/my_pkg/app.py to import utils. I want to call that Python file from anywhere. For example, I want to be in my_app and run python my_pkg/app.py.

Adding the following line in app.py throws the exception ModuleNotFoundError: No module named my_app:

from my_app.my_pkg import utils

I know I can add the path to sys.path but I don't want to do that. I don't understand why Python can't consider the above project structure as a package and just import the files. I find it really ugly to add paths to sys to get Python to find the files!

Any suggestions?

Phrixus
  • 1,209
  • 2
  • 19
  • 36
  • 1
    What if you do `from . import utils`? – drum Apr 06 '23 at 17:09
  • 1
    `from my_app.my_pkg` means that `my_pkg` is a subdirectory of `my_app`. – Barmar Apr 06 '23 at 17:09
  • Sorry my_pkg is a subdir – Phrixus Apr 06 '23 at 17:09
  • Doing `from . import utils` says `ImportError: attempted relative import with no known parent package` – Phrixus Apr 06 '23 at 17:11
  • @drum that wouldn't work unless you ran it with `python -m my_pkg.app`. – Axe319 Apr 06 '23 at 17:13
  • Sorry, but that's just not how Python works. You are not using `app.py` as a package. You are using it as an application, and that's the problem. If you had imported `app` through the `my_pkg` package, it would work. Given that structure, you absolutely need to modify `sys.path` to tell Python where to find your files. – Tim Roberts Apr 06 '23 at 17:13
  • @TimRoberts there's no need to modify `sys.path`. Just run it as a module and use relative imports. – Axe319 Apr 06 '23 at 17:17
  • "I know I can add the path to sys.path but I don't want to do that." - too bad; `sys.path` **is how Python decides** where to look for absolute imports. If you don't want that, use a relative import instead. "I don't understand why Python can't consider the above project structure as a package and just import the files." Using absolute import, by defintion, is explicitly disregarding any package structure. If you want to treat the project structure as a package, that is what relative import is for. – Karl Knechtel Apr 07 '23 at 07:27
  • `ImportError: attempted relative import with no known parent package` - yes; *relative* import on the other hand requires Python to know *where the top level of the package is*; it **does not** infer this from filesystem structure - the leading `.` in a relative import represent **package hierarchy** levels, **not** directories. – Karl Knechtel Apr 07 '23 at 07:29

1 Answers1

0

try this

import my_pkg.utils

or

import sys
sys.path.append("./')

import my_pkg.utils
Robert Sibanda
  • 255
  • 1
  • 4