My project has this kind of structure:
mypackage
|
|-- __init__.py
|
|-- file.py
|
|-- subpackage
|
|-- __init__.py
|
|-- function.py
How do I import the modules in the subpackage from file.py?
I tried a couple of things like simply import subpackage or from subpackage import function but all of them lead to ModuleNotFoundError: No module named 'subpackage'.
from . import subpackage has no error message but I don't know how to access the module with that.
asked Apr 3, 2021 at 12:03
StrangeGirlMurph
3511 gold badge3 silver badges17 bronze badges
2 Answers 2
I solved it by using:
from mypackage.subpackage import function
answered Apr 3, 2021 at 13:22
StrangeGirlMurph
3511 gold badge3 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
astrochun
Explicit is always better than implicit.
Just use
from subpackage import function
You propably are not in mypackage directory
3 Comments
StrangeGirlMurph
Thanks for your answer but when I type ´from subpackage import function´ in file.py I get: ModuleNotFoundError: No module named 'subpackage'
Kamil Kozioł
You have to run
file.py from mypackage directoryastrochun
For a bit more explicitness, I recommend
from .subpackage import functionlang-py
from subpackage import functionsubpackage.function()on a separate line to call a specific function