shellwhale
shellwhale

Reputation: 902

Import and run a subpackage from within a package

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

Upvotes: 2

Views: 1269

Answers (1)

EntGriff
EntGriff

Reputation: 875

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

Upvotes: 2

Related Questions