'Import a function from a module in another folder in parent directory

I have been trying unsuccessfully to solve this for hours now. This is my folder structure.

/parent_folder
      main.py
      module1/
        script1.py
      module2/
        script2.py

script2.py has only this inside:

def subtract_numbers(x, y):
    return x - y

I want script1.py to be able to call this function. I have:

from ..module2.script2 import subtract_numbers

result_subtraction = subtract_numbers(5, 5)
print(result_subtraction)

I get ImportError: attempted relative import with no known parent package

I have tried many different permutations in the import line in scrip1.py but i get the same error. I also have to note that i have __init__.py files in the two folders.

How exactly can i call the function in script2.py?



Solution 1:[1]

This is what worked for me.

I exported the directory of the parent directory (/parent_folder) to the PYTHONPATH.

export PYTHONPATH=$PYTHONPATH:/home/username/Desktop/parent_folder

Then, inside file module1/script1.py, i had this line changed:

from module2.script2 import subtract_numbers

Now i can call the script script1.py that calls the function declared in module2/script2.py with python script1.py and it will work.

I also have to note that i have __init__.py files everywhere (in the parent directory and both subfolders), but i am now sure if this is vital.

Solution 2:[2]

Relative imports cannot go back to a higher level than the one from which the python call was originated. So, your problem here is that you are invoking script1.py directly from the module1 directory. I guess something like this:

user:/path/to/parent/module1$ python script1.py

So you will need to make your call to script1.py from a level where you can actually see script2.py.

First, change your relative import to absolute import in script1.py:

from module2.script2 import subtract_numbers

Then, move back to the parent directory of module1 and run the module as a script from there (note the location in the prompt):

user:/path/to/parent$ python -m module1.script1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1584421
Solution 2