-1

python import from different level directory getting import error

Directory structure.

# all __init__.py files are empty



import/
├── helpers
│   ├── __init__.py
│   ├── helper1
│   │   ├── __init__.py
│   │   ├── helper1_module1.py
│   │   └── helper1_module2.py
│   └── helper2
│       ├── __init__.py
│       ├── helper2_module1.py
│       └── helper2_module2.py
└── services
    ├── __init__.py
    ├── service1
    │   ├── __init__.py
    │   └── service1_api.py
    └── service2

helper1_module1.py

class Helper1Module1():
    def function1(self):
        print("executed from Helper1Module1 Class function1")

    def function2(self):
        print("executed from Helper1Module1 Class function2")

service1_api.py

from helpers.helper1.helper1_module1 import Helper1Module1

h = Helper1Module1()
h.function1()

Error:

python3 services/service1/service1_api.py 
Traceback (most recent call last):
  File "services/service1/service1_api.py", line 1, in <module>
    from helpers.helper1.helper1_module1 import Helper1Module1
ModuleNotFoundError: No module named 'helpers'

How to fix this?

Python: python3.6 and above OS: Linux

Vidya
  • 547
  • 1
  • 10
  • 26
  • Try adding an `__init__.py` into the `helpers` directory. – a_guest Jan 23 '22 at 18:23
  • added still same issue – Vidya Jan 23 '22 at 18:42
  • I tried to reproduce the issue with Python 3.6 - 3.9 but I couldn't. It worked without problem for me. So it seems you are doing something different than is described in your question. Please check carefully all the details in your question and add what's missing. – a_guest Jan 24 '22 at 08:25

1 Answers1

1

You have to set the file path (PYTHONPATH) manually to use the files from other directories.

You can export Environment Variable like

export PYTHONPATH=’path/to/directory’

Or you can use sys module: Importing files from different folder

  • That is not correct. Python will add the script's directory as well as the current working directory to `sys.path` automatically, i.e. any imports from these directories should work without problem. For that reason, imports need to be either (a) relative to the script's directory (`from ...helpers.helper1.helper1_module1 import Helper1Module1`), but then executed with the [`-m` flag](https://docs.python.org/3/using/cmdline.html#cmdoption-m) or (b) relative to the current working directory (as in the question). – a_guest Jan 24 '22 at 08:30