Reputation: 424
I have the following dir structure
mainpackage
├── __init__.py
└── subpackage
├── __init__.py
└── module.py
Module.py contains
def test():
print("test called")
Using python3 I am looking to make the module.py module available for import in the mainpackage namespace. So far my mainpackage __init__.py file looks like this
from .subpackage import module
I would like to be able to call
import mainpackage.module
but this throws
ImportError: No module named 'mainpackage.module'
Just for clarity, I am NOT looking to import the test function into the mainpackage namespace - I want the entire module. Is this possible ? Any help would be much appreciated.
Upvotes: 0
Views: 285
Reputation: 3711
As far as I know you cannot make a module of a subpackage available in the namespace of the mainpackage like you tried:
import mainpackage.module
looks for a module in the subdirectory of mainpackage
and not in any other (deeper) subdirectories.
What you tried in the mainpackage\__init.py__
is correct. Your
from .subpackage import module
will make the module availabe on mainpackage
level. If you type in an IPython console
import mainpackage
mainpackage.module
will give the following output
<module 'mainpackage.subpackage.module' from 'your\path\mainpackage\subpackage\module.py'>
but import mainpackage.module
still won't work. If you now want to use module
as an instance you have to use
from mainpackage import module
which will allow you to use your function like this
module.test
Upvotes: 1
Reputation: 335
Import it this way from mainpackage.subpackage import module
and you don't need from .subpackage import module
in the init file
Upvotes: 0