0
votes

I need some help. I have been stuck with this for a while. I cannot figure out how and what to do.

I have a directory "folder" with the below structure.

.
├── folder1
│   ├── folder3
│   │   ├── a.py
│   │   └── __init__.py
│   └── __init__.py
├── folder2
│   ├── b.py
│   └── __init__.py
└── __init__.py

What I want to basically do is import a function in the "folder2/b.py" python file into "folder1/folder3/a.py". And I want to run the 'a.py' file from "folder1/folder3/" directory.

Let me illustrate this with an example. Suppose I have a function 'hello' in 'b.py'.

def hello():
    print("Hello world!")

And I have another file 'a.py' like this.

from b import hello

def hello1():
   print("Hello World!!")

I want to navigate to the 'folder3' directory.

cd folder1/folder3

And run the python file 'a.py' as follows.

python a.py

Doing so is giving me the below error.

ValueError: attempted relative import beyond the top-level package

I googled for a while and tried solving this with these resources (Import a module from a relative path, relative path not working even with init.py, How to fix “Attempted relative import in non-package” even with init.py).

The only method that worked so far is by using "sys.append" in 'a.py' like below. However, I have read that this usage is very unprofessional and highly unrecommended.

import sys
sys.path.append("D:/folder")

from folder2 import b

If you have dealt with such a setup/issue before, please help me out. Thanks!

1
The question is why does your setup look like this. Normally your project resides in the root directory and any other package your project requires is installed through pip or are present as children of your root folder. So there should be no reason to go one folder level up. You should turn it into a python package. Your project shouldn't reach a beyond the top level folder. - Tin Nguyen
Which OS? At least in Linux this is usually this is done by adding folder2 to the PYTHONPATH environment variable. - Jonatan Öström
@JonatanÖström Yes. But I don't want to use the PYTHONPATH approach. Any other ideas? - Sudheer Raja
@TinNguyen I don't agree, this seems normal to me. - Jonatan Öström
Then maybe see this question stackoverflow.com/questions/67631/… on how to import from absolute path using importlib. - Jonatan Öström

1 Answers

-1
votes

Try adding your root folder to your python path.