Home > Enterprise >  Import a function from a module in another folder in parent directory
Import a function from a module in another folder in parent directory

Time:05-11

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

  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?

CodePudding user response:

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
  • Related