0

I am not able to do absolute import in my python project. I referred to Importing modules from parent folder but all the approaches had some drawback.

Following is my directory structure. All my source code are present in Bank/src/

structure

File contents are

module1a.py

DEMO = '123'

module2a.py

from module1.module1a import DEMO
print (DEMO)

a.py

from module1 import module1a
print (module1a.DEMO)

I want to execute my code from bank directory

When I execute a.py it works

(base) ➜  Bank python src/a.py
123

When I execute module2a.py it fails

(base) ➜  Bank python src/module2/module2a.py
Traceback (most recent call last):
  File "src/module2/module2a.py", line 1, in <module>
    from module1.module1a import DEMO
ModuleNotFoundError: No module named 'module1'

Yes, my src is not in PYTHONPATH that's why it is failing.

I tried the following ways and all works

Approach 1:

(base) ➜  Bank PYTHONPATH=src python src/module2/module2a.py
123

Is it a good practice?

Approach 2:

Using something like this.

import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

Issue: I need to add it in all python files which I execute (in case of multiple entry points in the project)

Approach 3:

By creating setup using setuptools

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())

Issue: since my code is in src directory, I am not able to change package name, and I have to import like from src.module1.module1a import DEMO I want something like from myproject.module1.module1a import DEMO

Rahul Kumar
  • 2,184
  • 3
  • 24
  • 46
  • Your third item doesn't seem to be complete. If you create an installable module and install it (perhaps with `pip install -e .`in your virtual environment) you should be able to use the module as if it was installed system-wide. – tripleee Nov 29 '19 at 06:18
  • Also `PYTHONPATH=src python -m myproject` – tripleee Nov 29 '19 at 06:19
  • if you're running `module2a.py` from your module2a directory, then you could simply add `sys.path.append(..)` to the top of your module before importing your other modules. – Farhood ET Nov 29 '19 at 06:51
  • @tripleee Yes did in my environemnt using pip install -e . as suggested by @np8 in that link that I shared on the top. But I want to import it as `myproject` and not `src` – Rahul Kumar Nov 29 '19 at 08:03
  • Maybe add `package_dir={'': 'src'},` to the `setup()` parameters. – tripleee Nov 29 '19 at 08:06

0 Answers0