1

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.

inquilabee
  • 713
  • 1
  • 11
  • 23
  • 2
    Your imports should work correctly if you set your `PYTHONPATH` environment variable. Try running: `PYTHONPATH=. python app1/hello.py` (assuming you're on linux) - Note: I use virtualenv to solve this problem instead. – byxor Apr 27 '19 at 19:16
  • @byxor, I had to manually add `Projects` directory to PYTHONPATH, is this the recommeded way while starting every new project? – inquilabee Apr 27 '19 at 19:46
  • 1
    Not really. Most people use `virtualenv` or the newer tool, `pipenv`. It will automatically set the PYTHONPATH to the desired root of your project (so you don't have to). --- There are many good tutorials that explain what those tools are for. – byxor Apr 27 '19 at 21:43

0 Answers0