1

Here's my project structure:

py_workshop/
├── app/
│   ├── __init__.py
│   ├── script.py
│   └── time_module.py
└── tests/
    └── test_time_module.py

time_module.py's content:

import datetime


def current_time():
    return datetime.datetime.now().strftime("%H:%M:%S")

script.py's content:

from time_module import current_time

print(current_time())

test_time_module.py's content:

from app.time_module import current_time

print(current_time())

When I import current_time() from "app.time_module" into "test_time_module.py" I get this error:

Traceback (most recent call last): File "H:\dev\py-workshop\tests\test_time_module.py", line 1, in from ..app.time_module import * ImportError: attempted relative import with no known parent package

I've googled for a possible solution and found out that I should add init.py to app/ and time_module/ to fix the error but it resulted in the same error.

I this thread I found an answer that says I for a seperate unit as in my case I should change PYTHONPATH with PYTHONPATH=$PYTHONPATH${PYTHONPATH:+:}$PWD/lib/ so I ran: PYTHONPATH=$PYTHONPATH${PYTHONPATH:+:}$PWD/app/

still no success!

I expect that when I run $ python tests/test_time_module.py I get the current time in this format: H:M:S

I'm very confused at this moment.

Edit 1:

Current solution:

import sys

sys.path.append('../')


if __name__ == '__main__':
    from app.time_module import *
    print(current_time())```
Navid
  • 33
  • 6
  • 1
    Add the parent folder to the system path using `import sys` and `sys.path.append('../')` – Michael Cao May 04 '23 at 21:08
  • This would only work if I changed my test_time_module.py to: import sys sys.path.append('../') if __name__ == '__main__': from app.time_module import * print(current_time()) is this how am I supposed to write it typically or there are better alternatives? – Navid May 04 '23 at 21:13
  • You can add the absolute path to `py_workshop` instead of using a relative path. – Michael Cao May 04 '23 at 21:15
  • You could install your project in [editable mode](https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-e) – Philip Wrage May 04 '23 at 21:19

1 Answers1

2

The PYTHONPATH variable should contain the directory your app is located in, not the app directory itself.

So in your case it should be H:\dev\py-workshop\.

It looks like you're using Windows, so you should be able to set the PYTHONPATH using either Windows Command Prompt or PowerShell:

setx PYTHONPATH "%PYTHONPATH%;H:\dev\py-workshop\" /m

Then you can double-check that the PYTHONPATH is set correctly:

set PYTHONPATH
Anton Petrov
  • 315
  • 1
  • 3
  • 12