-1

I have the following project architecture (simplified):

root/ main.py mypackage/ __init__.py module1.py module2.py ci_scripts/ script1.py script2.py doc/ doc 

where the root is nothing more than a folder.

How do I import module1 and module2 in script1.py for example?

I tried to:

  • Add the relative path inside script1.py: from ..mypackage import module1
  • The absolute path
  • Use of sys package to append the path of mypackage

To give more context, I was expecting that the following code inside of script1.py would work:

from ..mypackage import module1 module1.func1() 

but I get:

ImportError: attempted relative import with no known parent package

And when I try to use the absolute path:

import mypackage.module1 module1.func1() 

I get the following error:

ModuleNotFoundError: No module named 'mypackage'

5
  • Does this answer your question? stackoverflow.com/questions/4209641/… Commented Feb 9, 2023 at 9:55
  • No, in theory I know how it should be done but in my example, importing with relative or absolute paths does not work Commented Feb 9, 2023 at 10:00
  • You should edit your question to reflect what you are asking then. Currently you are asking what is the most pythonic way to import, not how to troubleshoot failing imports. Commented Feb 9, 2023 at 10:02
  • 1
    Does this answer your question? When to use Absolute Path vs Relative Path in Python Commented Feb 9, 2023 at 17:35
  • I followed the recommandations from here but Adrian Mole's answer is in the same spirit and it did the trick! Thank you Commented Feb 15, 2023 at 10:55

1 Answer 1

1

Your absolute import probably does not work because your root folder is not set to be mypackage. You can see here on how to do that: python: Change the scripts working directory to the script's own directory

Alternatively, you can use relative imports. You are correctly importing with from ..mypackage import module1 - however, you cannot execute a script directly with a relative import. You need to import the script into some other module which you are then executing. See explanation here: Relative imports in Python 3

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.