There are a number of similar SO questions but I believe my concern is different. Please read the problem completely.
When I run tree
command in my project directory named Project
, it gives me the following
.
├── app1
│ ├── __init__.py
│ └── hello.py
└── app2
├── __init__.py
└── utils.py
Contents of hello.py
from math import factorial
from app2.utils import hello
if __name__ == "__main__":
hello()
print(factorial(5))
contents of utils.py
def hello():
print("Hello")
if __name__ == "__main__":
hello()
Running python app2/utils.py
from Project
directory gives me the following:
hello
However, running python app1/hello.py
from the same Project
directory results in an error.
Traceback (most recent call last):
File "app1/hello.py", line 3, in <module>
from app2.utils import hello
ModuleNotFoundError: No module named 'app2'
After reading a number of SO answers, I found a workaround this problem. The answer suggest adding below lines at the top of hello.py
import sys
sys.path.append(".")
The suggested approach does solve my problem but the same does not seem pythonic to me (adding same set of lines in each file).
Are there any better ways to achieve the same?
Thanks.