2

I'm looking for a way to import a subpackage from within a package in Python 3. Consider the following structure :

├── main.py
└── package
    ├── subpackage
    │   └── hello.py
    └── test.py

What I would like to do is use a function that inside hello.py from within test.py (which is launched by main.py)

main.py

from package.test import print_hello

print_hello()

package/test.py

from subpackage.hello import return_hello

def print_hello():
    print(return_hello())

package/subpackage/hello.py

def return_hello():
    return "Hello"

But I'm getting the following error :

Traceback (most recent call last):
  File ".\main.py", line 1, in <module>
    from package.test import print_hello
  File "D:\Python\python-learning\test\package\test.py", line 1, in <module>
    from subpackage.hello import return_hello
ModuleNotFoundError: No module named 'subpackage'

I tried putting a . in test.py and it worked, but my linter does not like it.

enter image description here

What am I doing wrong ?


edit : I managed to use an absolute path as recommended but now when I try to put everything in a subfolder pylint is not able to import.

└── src
    ├── main.py
    └── package
        ├── subpackage
        │   └── hello.py
        └── test.py

enter image description here

shellwhale
  • 555
  • 4
  • 22

1 Answers1

2

Just use

from .subpackage.hello import return_hello

instead of

from subpackage.hello import return_hello

in your test.py file and read this guide for better understanding how imports works in python.

You can see fixed result here : https://repl.it/@ent1c3d/SoupySadUnderstanding

EntGriff
  • 605
  • 5
  • 11
  • That is exactly what my linter does not like as I said on my post – shellwhale Feb 02 '19 at 22:35
  • Okay, I understand, so you see answers on this question : https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import – EntGriff Feb 02 '19 at 22:45