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/
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