-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'

TylerH
  • 20,799
  • 66
  • 75
  • 101
kurisukun
  • 74
  • 6
  • Does this answer your question? https://stackoverflow.com/questions/4209641/absolute-vs-explicit-relative-import-of-python-module – oskros Feb 09 '23 at 09:55
  • No, in theory I know how it should be done but in my example, importing with relative or absolute paths does not work – kurisukun Feb 09 '23 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. – oskros Feb 09 '23 at 10:02
  • 1
    Does this answer your question? [When to use Absolute Path vs Relative Path in Python](https://stackoverflow.com/questions/44772007/when-to-use-absolute-path-vs-relative-path-in-python) – Adrian Mole Feb 09 '23 at 17:35
  • I followed the recommandations from [here](https://docs.python-guide.org/writing/structure/#test-suite) but Adrian Mole's answer is in the same spirit and it did the trick! Thank you – kurisukun Feb 15 '23 at 10:55

1 Answers1

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

oskros
  • 3,101
  • 2
  • 9
  • 28