2

If I have a file structure like this:

backend
├─api_layer
  ├─ app.py
├─database_layer
  ├─ service.py

In app.py, how do I import from service.py?

I've tried

import sys
# setting path
sys.path.append('../database_layer')
import database_layer.service as DBService

I've also tried to add an empty __init__.py file to database_layer directory.

None of them work. When I run python3 app.py, they all have ModuleNotFoundError: No module named 'database_layer' error. Is importing from parent's subdirectory even possible in python?

kichik
  • 33,220
  • 7
  • 94
  • 114
HRL
  • 21
  • 5
  • 1
    ``..`` is relative to the current working directory, not the directory with the file. You can do `import os` and use `os.path.abspath(os.path.dirname('__file__')+'/../database_layer')`. – Tim Roberts Apr 02 '23 at 18:08
  • 4
    **don't mess with the `sys.path`** Make your project installable then install it. Then just use `import database_layer.service` – juanpa.arrivillaga Apr 02 '23 at 18:36

1 Answers1

-1

I usually do:

import sys
sys.path.insert( 1, "../database_layer")
import service

I'm inserting instead of appending because when you append your directory will be looked at after python search all librairies. A "service" module (not yours) may exist somewhere else.
With insertion, your directory will be searched in priority (just after searching in your backend directory). But your real mistake was that your imported with a path. Do not.

user3435121
  • 633
  • 4
  • 13
  • I've tried it. It says no module named service still... I also tried "import database_layer.service", also don't work... – HRL Apr 03 '23 at 14:34