0

I am fairly new to Python, and despite searching all over and following many guides on this site, I am still stuck with a strange issue.

Folder structure is as follows

ProjectFolder
    |  
    --> tests
    |     |
    |     --> test_this.py
    |     -->__init__.py
    --> app.py
    --> __init__.py

I am trying to simply import something from app.py into test_this.py

I have tried a few different things so far,
from app import func - This obviously won't work as it is not in the same dir
So I tried:
from ..app import func and from . app import func This gives the following error:

Exception has occurred: ImportError
attempted relative import with no known parent package

Clearly I am missing or not understanding something here. I thought that I would be able to import it as I have that __init__.py file in the directory I am trying to import from.
Any chance someone could clarify this for me?

  • How are you running test_this.py? – aaron Mar 07 '22 at 02:01
  • I am running this all in vscode, I am just running it in the debugger with ctrl+F5, or just running it with F5. I just tried running it in the console, same error. – Kyle Crawford Mar 07 '22 at 02:05
  • May be this issue can help you: https://stackoverflow.com/questions/71201484/how-to-resolve-python-module-not-found-error/71201672#71201672 – WENJUN CHI Mar 07 '22 at 02:20
  • Does this answer your question? [How to set up VS Code for imported modules to work in both debug and test?](https://stackoverflow.com/a/71007517/8601760) – aaron Mar 07 '22 at 02:57
  • Unfortunately not, as the script does not work when run in command prompt as well. It's not an isolated issue with VS code. I am having some luck using sys.path and adding the path to the imported file to that. I just need to be able to enter a relative path into that now. – Kyle Crawford Mar 07 '22 at 03:07
  • How are you running test_this.py in command prompt? – aaron Mar 07 '22 at 03:46
  • it is usual to import modules from the same forlder or subfolders (children folders) and nto the other way around (from the parent folder). So in the case of the structure given in the question `app.py` would import from `test_this.py`. – D.L Mar 07 '22 at 11:59

1 Answers1

0

So the trick for me was to add the files I needed to the sys.path variable.

import sys, os
from pathlib import Path

path = Path(__file__)
sys.path.insert(0, os.path.join(sys.path[0], path.parent.parent.absolute()))

This allowed me to reference a file in a parent or sibling folder without errors.