Reputation: 902
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)
from package.test import print_hello
print_hello()
from subpackage.hello import return_hello
def print_hello():
print(return_hello())
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.
What am I doing wrong ?
└── src
├── main.py
└── package
├── subpackage
│ └── hello.py
└── test.py
Upvotes: 2
Views: 1269
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