Nadroihr
Nadroihr

Reputation: 17

Absolute and Relative Imports - Importing module in subfolder2 from subfolder1

Project Structure

I have the following project structure:

pythonProject\
    modules\
        __init__.py
        module1\
            __init__.py
            script1.py
        module2\
            __init__.py
            script2.py

the content of script2.py is:

def script2_function():
  return "Import worked successfully"

Absolute Import

When trying an absolute import, the content of script1.py is:

from modules.module2.script2 import script2_function

print(script2_function())

When running script1.py (both from the project root and the module1 directory) I get the following error:

ModuleNotFoundError: No module named 'modules'


Relative Import

When trying an absolute import, the content of script1.py is:

from ..module2.script2 import script2_function

print(script2_function())

When running script1.py (both from the project root and the module1 directory) I get the following error:

ImportError: attempted relative import with no known parent package


I honestly cannot understand what I am doing wrong, and tried following several guides and stack answers, but nothing has solved this issue. Can you please explain me how to solve it, so I can better understand both relative and absolute python imports?

Thank you in advance for any help provided.

Upvotes: 0

Views: 47

Answers (1)

Matt Arnold
Matt Arnold

Reputation: 46

If I am understanding you correctly you could either change directory to the pythonProject directory and run python3 -m modules.module1.script1. The import statement is relative to where you are running Python from.

The other option of course would be to have script1.py in the project root which is similar to the above and for many projects may make more sense.

For both of the above the import statement in script1.py can either be from modules.module2.script2 import script2_function or from ..module2.script2 import script2_function.

Apologies if I have misunderstood the question.

Upvotes: 1

Related Questions